Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(search): direct news links, combined web indexes, provider search when blocked

Salman Qureshi2ed59b2ccdd0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f77394a9..b2c8565e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,13 @@
# Changelog
+## Unreleased
+
+### Web search
+- **News links open the article.** News search used Google News first, whose links are Google redirects (`news.google.com/rss/articles/…`) that can't be turned into the publisher's address. Bing News now comes first and its links are unwrapped to the real article; Google News is the fallback, and its links are marked as redirects.
+- **Two web indexes, combined.** Brave and DuckDuckGo (its html and lite pages) both answer some automated requests and block others, by client fingerprint and rate. `web_search` now asks them in turn and combines relevant results until it has enough, instead of stopping at the first engine with one hit.
+- **When the free engines are blocked, your own provider searches.** If Brave and DuckDuckGo both refuse, or what came back is too thin, `web_search` uses the official web search of a provider you already set up: Anthropic (Claude Haiku with the web search tool), then OpenAI. No new key; a small cost only on this path.
+- **You can see what happened.** Every result ends with the trail, for example `Searched: Brave: blocked (HTTP 429) → DuckDuckGo: 5 results`, so "nothing found" and "everything was blocked" read differently.
+
## 1.4.1 — Mercury learns how you work, saves its own skills, and searches again
### Owner Model: Mercury learns how to work with you (ADR-026)
diff --git a/src/capabilities/web/provider-search.ts b/src/capabilities/web/provider-search.ts
new file mode 100644
index 00000000..42c0838c
--- /dev/null
+++ b/src/capabilities/web/provider-search.ts
@@ -0,0 +1,99 @@
+import type { SearchResult } from './web-search.js';
+
+/**
+ * Last-resort web search through a model provider the owner already set up
+ * (Anthropic or OpenAI). The free engines are scraped, and scraping gets
+ * blocked; these are official search APIs behind keys Mercury already has,
+ * so no new key is ever asked for. They cost a little per search, which is
+ * why web_search only reaches them when every free engine came back empty.
+ */
+
+export interface ProviderKey {
+ name: 'anthropic' | 'openai';
+ apiKey: string;
+ baseUrl: string;
+}
+
+const TIMEOUT_MS = 30_000;
+/** A small, fast model is enough: it only runs the search. */
+const ANTHROPIC_SEARCH_MODEL = 'claude-haiku-4-5';
+const OPENAI_SEARCH_MODEL = 'gpt-4.1-mini';
+
+async function post(url: string, headers: Record<string, string>, body: unknown): Promise<unknown> {
+ const ac = new AbortController();
+ const timer = setTimeout(() => ac.abort(), TIMEOUT_MS);
+ try {
+ const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', ...headers }, body: JSON.stringify(body), signal: ac.signal });
+ const text = await res.text();
+ if (!res.ok) throw new Error(`HTTP ${res.status}${text ? `: ${text.slice(0, 160)}` : ''}`);
+ return JSON.parse(text);
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+/** Anthropic's server-side web_search tool: results come back as web_search_result blocks. */
+export function parseAnthropicSearch(data: unknown, max: number): SearchResult[] {
+ const out: SearchResult[] = [];
+ const blocks = (data as { content?: Array<Record<string, unknown>> })?.content ?? [];
+ for (const block of blocks) {
+ if (block.type !== 'web_search_tool_result' || !Array.isArray(block.content)) continue;
+ for (const hit of block.content as Array<Record<string, unknown>>) {
+ if (hit.type !== 'web_search_result' || typeof hit.url !== 'string') continue;
+ out.push({ title: String(hit.title ?? hit.url), url: hit.url, snippet: '', date: typeof hit.page_age === 'string' ? hit.page_age : undefined });
+ if (out.length >= max) return out;
+ }
+ }
+ // The model's own answer cites the pages it used, with the quoted text: use
+ // those quotes as snippets.
+ for (const block of blocks) {
+ for (const c of (block.citations as Array<Record<string, unknown>> | undefined) ?? []) {
+ const hit = out.find((r) => r.url === c.url);
+ if (hit && !hit.snippet && typeof c.cited_text === 'string') hit.snippet = c.cited_text.slice(0, 300);
+ }
+ }
+ return out;
+}
+
+/** OpenAI's Responses API web_search tool: sources arrive as url_citation annotations. */
+export function parseOpenAiSearch(data: unknown, max: number): SearchResult[] {
+ const out: SearchResult[] = [];
+ const seen = new Set<string>();
+ for (const item of (data as { output?: Array<Record<string, unknown>> })?.output ?? []) {
+ for (const part of (item.content as Array<Record<string, unknown>> | undefined) ?? []) {
+ const text = typeof part.text === 'string' ? part.text : '';
+ for (const a of (part.annotations as Array<Record<string, unknown>> | undefined) ?? []) {
+ if (a.type !== 'url_citation' || typeof a.url !== 'string') continue;
+ const url = a.url.replace(/[?&]utm_source=openai$/, '');
+ if (seen.has(url)) continue;
+ seen.add(url);
+ const start = typeof a.start_index === 'number' ? a.start_index : 0;
+ out.push({ title: String(a.title ?? url), url, snippet: text.slice(Math.max(0, start - 200), start).replace(/\s+/g, ' ').trim().slice(-300) });
+ if (out.length >= max) return out;
+ }
+ }
+ }
+ return out;
+}
+
+export async function providerSearch(key: ProviderKey, query: string, max: number): Promise<SearchResult[]> {
+ if (!query.trim()) return [];
+ const ask = `Search the web for: ${query}\nList the most relevant pages. Be brief.`;
+ if (key.name === 'anthropic') {
+ const base = (key.baseUrl || 'https://api.anthropic.com').replace(/\/+$/, '').replace(/\/v1$/, '');
+ const data = await post(`${base}/v1/messages`, { 'x-api-key': key.apiKey, 'anthropic-version': '2023-06-01' }, {
+ model: ANTHROPIC_SEARCH_MODEL,
+ max_tokens: 600,
+ tools: [{ type: 'web_search_20250305', name: 'web_search', max_uses: 1 }],
+ messages: [{ role: 'user', content: ask }],
+ });
+ return parseAnthropicSearch(data, max);
+ }
+ const base = (key.baseUrl || 'https://api.openai.com/v1').replace(/\/+$/, '');
+ const data = await post(`${base}/responses`, { Authorization: `Bearer ${key.apiKey}` }, {
+ model: OPENAI_SEARCH_MODEL,
+ tools: [{ type: 'web_search' }],
+ input: ask,
+ });
+ return parseOpenAiSearch(data, max);
+}
diff --git a/src/capabilities/web/web-search.test.ts b/src/capabilities/web/web-search.test.ts
index b876fe72..365dd8a6 100644
--- a/src/capabilities/web/web-search.test.ts
+++ b/src/capabilities/web/web-search.test.ts
@@ -44,7 +44,7 @@ const defaultFetch = routes({ 'search.brave.com': BRAVE, 'news.google.com': GOOG
vi.mock('../../utils/ssrf.js', () => ({ guardedFetch: vi.fn() }));
-import { createWebSearchTool, parseBrave, parseRss, relevant, resetBraveCooldown, searchQueryFromUrl, webSearch } from './web-search.js';
+import { createWebSearchTool, directLink, parseBrave, parseDdg, parseRss, relevant, resetBraveCooldown, searchQueryFromUrl, webSearch } from './web-search.js';
import { guardedFetch } from '../../utils/ssrf.js';
vi.mocked(guardedFetch).mockImplementation(defaultFetch as never);
@@ -148,6 +148,88 @@ describe('web_search', () => {
const out = await t.execute({ query: '', kind: 'news' }, {});
expect(out).toMatch(/News results from Google News[\s\S]*1\. Envoy meets leader in Moscow \(BBC · Wed, 21 Oct 2026\)/);
vi.mocked(guardedFetch).mockImplementation(async () => new Response('', { status: 500 }));
- expect(await t.execute({ query: 'x' }, {})).toMatch(/^Error: web search is unavailable/);
+ expect(await t.execute({ query: 'x' }, {})).toMatch(/^Error: web search found nothing: no source found anything \(Brave: HTTP 500; DuckDuckGo: HTTP 500/);
+ });
+
+ it('parses DuckDuckGo html and lite pages: real links out of the redirect, ads dropped', () => {
+ const html = `<a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fpandoc.org%2Fepub.html&amp;rut=abc">Pandoc - Creating an ebook with pandoc</a>
+ <a class="result__snippet" href="x">Starting with version 1.6, <b>pandoc</b> can produce EPUB.</a>
+ <a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fduckduckgo.com%2Fy.js%3Fad%3D1">Sponsored</a>`;
+ expect(parseDdg(html, 5)).toEqual([{ title: 'Pandoc - Creating an ebook with pandoc', url: 'https://pandoc.org/epub.html', snippet: 'Starting with version 1.6, pandoc can produce EPUB.' }]);
+ const lite = `<a rel="nofollow" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fwww.linkedin.com%2Fcompany%2Fcosmic-stack&amp;rut=x" class='result-link'>Cosmic Stack - LinkedIn</a>
+ <td class='result-snippet'>Cosmic Stack builds Mercury.</td>`;
+ expect(parseDdg(lite, 5)[0]).toEqual({ title: 'Cosmic Stack - LinkedIn', url: 'https://www.linkedin.com/company/cosmic-stack', snippet: 'Cosmic Stack builds Mercury.' });
+ });
+
+ it('news links open the article: Bing News redirects are unwrapped', () => {
+ expect(directLink('http://www.bing.com/news/apiclick.aspx?ref=FexRss&aid=&tid=1&url=https%3a%2f%2fkashmirlife.net%2fstory&c=2')).toBe('https://kashmirlife.net/story');
+ expect(directLink('https://kashmirlife.net/story')).toBe('https://kashmirlife.net/story');
+ const feed = `<rss><channel><item><title>Kashmir story</title><link>http://www.bing.com/news/apiclick.aspx?ref=FexRss&amp;url=https%3a%2f%2fkashmirlife.net%2fstory</link></item></channel></rss>`;
+ expect(parseRss(feed, 3)[0].url).toBe('https://kashmirlife.net/story');
+ });
+
+ it('news asks Bing News first, so links are direct; Google News is the fallback', async () => {
+ const bingNewsFeed = `<rss><channel><item><title>Kashmir story</title><link>http://www.bing.com/news/apiclick.aspx?url=https%3a%2f%2fkashmirlife.net%2fstory</link></item></channel></rss>`;
+ vi.mocked(guardedFetch).mockImplementation(routes({ 'bing.com/news': bingNewsFeed, 'news.google.com': GOOGLE_NEWS }) as never);
+ const r = await webSearch('kashmir', { kind: 'news' });
+ expect(r.engine).toBe('Bing News');
+ expect(r.results[0].url).toBe('https://kashmirlife.net/story');
+ });
+
+ it('combines engines until there are enough results, and records what each one did', async () => {
+ const oneHit = `<a href="https://www.typescriptlang.org/satisfies" target="_self" class="l1"><div class="title search-snippet-title" title="TypeScript satisfies operator">x</div></a><div class="content">satisfies</div>`;
+ const ddgPage = `<a class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.dev%2Fa">TypeScript satisfies explained</a><a class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.dev%2Fb">The satisfies operator in TypeScript</a><a class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.dev%2Fc">TypeScript satisfies vs as</a>`;
+ vi.mocked(guardedFetch).mockImplementation(routes({ 'search.brave.com': oneHit, 'html.duckduckgo.com': ddgPage }) as never);
+ const r = await webSearch('typescript satisfies operator', { max: 8 });
+ expect(r.engine).toBe('Brave + DuckDuckGo');
+ expect(r.results).toHaveLength(4);
+ expect(r.trail).toEqual(['Brave: 1 result', 'DuckDuckGo: 3 results']);
+ });
+
+ it('a bot challenge reads as "blocked" in the trail', async () => {
+ vi.mocked(guardedFetch).mockImplementation(routes({ 'search.brave.com': 429, 'duckduckgo.com': '<html>anomaly</html>', 'wikipedia.org': WIKI }) as never);
+ const r = await webSearch('canberra');
+ expect(r.trail.slice(0, 4)).toEqual(['Brave: blocked (HTTP 429)', 'DuckDuckGo: blocked (bot challenge)', 'DuckDuckGo Lite: blocked (bot challenge)', 'Wikipedia: 2 results']);
+ });
+
+ it('when the web indexes are blocked, the owner\'s own provider search answers (Anthropic first)', async () => {
+ vi.mocked(guardedFetch).mockImplementation(routes({ 'search.brave.com': 429, 'wikipedia.org': WIKI }) as never);
+ const realFetch = globalThis.fetch;
+ const calls: string[] = [];
+ globalThis.fetch = (async (url: string) => {
+ calls.push(String(url));
+ if (String(url).includes('anthropic')) return new Response(JSON.stringify({ content: [
+ { type: 'web_search_tool_result', content: [
+ { type: 'web_search_result', title: 'Dario Amodei', url: 'https://darioamodei.com/', page_age: 'October 2026' },
+ { type: 'web_search_result', title: 'Anthropic leadership', url: 'https://www.anthropic.com/company' },
+ ] },
+ { type: 'text', text: 'Dario Amodei is the CEO.', citations: [{ url: 'https://darioamodei.com/', cited_text: 'Dario Amodei, CEO of Anthropic' }] },
+ ] }), { status: 200 });
+ return new Response('no', { status: 500 });
+ }) as typeof fetch;
+ try {
+ const r = await webSearch('canberra', { providers: [{ name: 'anthropic', apiKey: 'sk-ant-test-key', baseUrl: 'https://api.anthropic.com' }, { name: 'openai', apiKey: 'sk-test-key-openai', baseUrl: 'https://api.openai.com/v1' }] });
+ expect(r.engine).toBe('Anthropic web search + Wikipedia');
+ expect(r.results[0]).toMatchObject({ title: 'Dario Amodei', url: 'https://darioamodei.com/', snippet: 'Dario Amodei, CEO of Anthropic' });
+ expect(r.trail.at(-1)).toBe('Anthropic web search: 2 results');
+ expect(calls).toEqual(['https://api.anthropic.com/v1/messages']); // OpenAI not needed
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+ });
+
+ it('a strong free answer never touches the paid provider search', async () => {
+ const page = Array.from({ length: 5 }, (_, i) => `<a href="https://example.dev/${i}" target="_self" class="l1"><div class="title search-snippet-title" title="Canberra page ${i}">x</div></a>`).join('');
+ vi.mocked(guardedFetch).mockImplementation(routes({ 'search.brave.com': page }) as never);
+ const realFetch = globalThis.fetch;
+ let paid = 0;
+ globalThis.fetch = (async () => { paid++; return new Response('{}'); }) as typeof fetch;
+ try {
+ const r = await webSearch('canberra', { providers: [{ name: 'anthropic', apiKey: 'sk-ant-test-key', baseUrl: '' }] });
+ expect(r.engine).toBe('Brave');
+ expect(paid).toBe(0);
+ } finally {
+ globalThis.fetch = realFetch;
+ }
});
});
diff --git a/src/capabilities/web/web-search.ts b/src/capabilities/web/web-search.ts
index f7e4e58c..8101b1d7 100644
--- a/src/capabilities/web/web-search.ts
+++ b/src/capabilities/web/web-search.ts
@@ -1,12 +1,15 @@
import { tool, zodSchema } from 'ai';
import { z } from 'zod';
import { guardedFetch } from '../../utils/ssrf.js';
+import { providerSearch, type ProviderKey } from './provider-search.js';
/**
* web_search: free, keyless search for the model.
*
- * web → Brave Search, then Wikipedia, Hacker News, Bing News, Google News, Bing RSS
- * news → Google News RSS, recent first, then Bing News, Hacker News
+ * web → Brave Search, DuckDuckGo (html, then lite), then Wikipedia, Hacker News,
+ * Bing News, Google News, Bing RSS
+ * news → Bing News (direct article links), then Google News (top stories, or
+ * when Bing has nothing; its links are Google redirects), Hacker News
*
* Every answer must mention the query (relevant()); an engine serving junk
* counts as empty and the next one is tried.
@@ -53,11 +56,28 @@ function tag(item: string, name: string): string {
return m ? decode(m[1]) : '';
}
+/**
+ * The publisher's own URL behind a news-feed redirect. Bing News wraps every
+ * article as bing.com/news/apiclick.aspx?…&url=<the article>; unwrap it so the
+ * owner gets a link that opens the story. (Google News links can't be
+ * unwrapped without running its JavaScript, which is why Bing News comes first.)
+ */
+export function directLink(link: string): string {
+ try {
+ const u = new URL(link);
+ if (/(^|\.)bing\.com$/.test(u.hostname) && /\/apiclick\.aspx$/i.test(u.pathname)) {
+ const target = u.searchParams.get('url');
+ if (target && /^https?:\/\//i.test(target)) return target;
+ }
+ } catch { /* not a URL: leave it */ }
+ return link;
+}
+
export function parseRss(xml: string, max: number): SearchResult[] {
const out: SearchResult[] = [];
for (const m of xml.matchAll(/<item>([\s\S]*?)<\/item>/gi)) {
const item = m[1];
- const url = tag(item, 'link');
+ const url = directLink(tag(item, 'link'));
const title = tag(item, 'title');
if (!url || !title || /bing\.com(:\d+)?\/search\?/.test(url)) continue;
const source = tag(item, 'source');
@@ -122,6 +142,53 @@ export function parseBrave(html: string, max: number): SearchResult[] {
return out;
}
+/**
+ * DuckDuckGo's no-JavaScript result pages (html. and lite.). Links come as
+ * duckduckgo.com/l/?uddg=<the page>; ads point back at duckduckgo.com and
+ * are dropped. DuckDuckGo answers some automated requests with a challenge
+ * page (HTTP 202, "anomaly"), which counts as a failure so the chain moves on.
+ */
+export function parseDdg(html: string, max: number): SearchResult[] {
+ const out: SearchResult[] = [];
+ const anchor = /<a[^>]*class=["'](?:result__a|result-link)["'][^>]*>[\s\S]*?<\/a>|<a[^>]*href="[^"]*"[^>]*class=["'](?:result__a|result-link)["'][^>]*>[\s\S]*?<\/a>/g;
+ const found = [...html.matchAll(anchor)];
+ for (let i = 0; i < found.length && out.length < max; i++) {
+ const tagText = found[i][0];
+ const href = /href="([^"]+)"/.exec(tagText)?.[1];
+ if (!href) continue;
+ let url = unescape(href);
+ try {
+ const u = new URL(url.startsWith('//') ? `https:${url}` : url);
+ url = u.searchParams.get('uddg') ?? u.href;
+ } catch { continue; }
+ if (!/^https?:\/\//.test(url) || /^https?:\/\/([a-z]+\.)?duckduckgo\.com\//.test(url)) continue;
+ const title = decode(tagText.replace(/^<a[^>]*>/, '').replace(/<\/a>$/, ''));
+ const start = (found[i].index ?? 0) + tagText.length;
+ const end = i + 1 < found.length ? found[i + 1].index ?? html.length : Math.min(html.length, start + 4000);
+ const scope = html.slice(start, end);
+ const snippet = /class=["'](?:result__snippet|result-snippet)["'][^>]*>([\s\S]*?)<\/(?:a|td|div)>/.exec(scope)?.[1] ?? '';
+ if (title) out.push({ title, url, snippet: decode(snippet).slice(0, 300) });
+ }
+ return out;
+}
+
+async function ddg(kind: 'html' | 'lite', query: string, max: number): Promise<SearchResult[]> {
+ if (!query.trim()) return [];
+ const ac = new AbortController();
+ const timer = setTimeout(() => ac.abort(), TIMEOUT_MS);
+ try {
+ const res = await guardedFetch(`https://${kind}.duckduckgo.com/${kind}/?q=${encodeURIComponent(query)}`, ac.signal, { 'User-Agent': UA, Accept: 'text/html' });
+ const body = await res.text();
+ if (res.status === 202 || /anomaly/i.test(body)) throw new Error('bot challenge');
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return parseDdg(body, max);
+ } finally {
+ clearTimeout(timer);
+ }
+}
+const ddgHtml = (q: string, n: number) => ddg('html', q, n);
+const ddgLite = (q: string, n: number) => ddg('lite', q, n);
+
/** Brave rate-limits per IP: after a 429 it is skipped for a minute rather than tried (and waited on) every query. */
const BRAVE_COOLDOWN_MS = 60_000;
let braveBlockedUntil = 0;
@@ -212,7 +279,9 @@ export function formatResults(results: SearchResult[], engine: string, query: st
const meta = [r.source, r.date ? new Date(r.date).toUTCString().slice(0, 16) : ''].filter(Boolean).join(' · ');
return `${i + 1}. ${r.title}${meta ? ` (${meta})` : ''}\n ${r.url}${r.snippet ? `\n ${r.snippet}` : ''}`;
});
- return `${kind === 'news' ? 'News' : 'Web'} results from ${engine} for "${query || 'top stories'}":\n\n${lines.join('\n')}`;
+ const viaGoogle = results.some((r) => /^https?:\/\/news\.google\.com\/rss\/articles\//.test(r.url));
+ const note = viaGoogle ? '\n\nNote: news.google.com links are Google redirects, not the publisher\'s page. Say so if you share them, and name the source site.' : '';
+ return `${kind === 'news' ? 'News' : 'Web'} results from ${engine} for "${query || 'top stories'}":\n\n${lines.join('\n')}${note}`;
}
const STOP = new Set(['the', 'and', 'for', 'with', 'what', 'who', 'how', 'are', 'was', 'is', 'of', 'in', 'on', 'to', 'a', 'an', 'best', 'top', 'latest', 'new', 'news', 'does', 'did', 'can', 'from', 'about', 'near', 'me', 'my', 'vs']);
@@ -246,36 +315,98 @@ function dedupe(results: SearchResult[]): SearchResult[] {
});
}
-export async function webSearch(query: string, opts: { kind?: 'web' | 'news'; max?: number } = {}): Promise<{ results: SearchResult[]; engine: string }> {
+export interface SearchOutcome {
+ results: SearchResult[];
+ /** The engines whose results are in the answer, e.g. "Brave + DuckDuckGo". */
+ engine: string;
+ /** What each engine tried did: "Brave: blocked (HTTP 429)", "DuckDuckGo: 6 results". */
+ trail: string[];
+}
+
+/** Results needed before the search stops asking more engines. */
+const ENOUGH = 4;
+
+/** A short reason a source failed, for the trail. */
+function why(err: unknown): string {
+ const m = (err as Error)?.message ?? String(err);
+ if (/429|challenge|rate-limited|captcha/i.test(m)) return `blocked (${m})`;
+ if (/abort/i.test(m)) return 'timed out';
+ return m;
+}
+
+/**
+ * The provider keys web_search may fall back to, set at boot from the owner's
+ * config (Anthropic first, then OpenAI). Empty means free engines only.
+ */
+let providerKeys: ProviderKey[] = [];
+export function setSearchProviders(keys: ProviderKey[]): void {
+ providerKeys = keys.filter((k) => k.apiKey && k.apiKey.length > 8);
+}
+
+export async function webSearch(query: string, opts: { kind?: 'web' | 'news'; max?: number; providers?: ProviderKey[] } = {}): Promise<SearchOutcome> {
const max = Math.max(1, Math.min(opts.max ?? 8, 15));
- // Every engine is free and keyless; no library. Brave is the main web
- // index (DuckDuckGo, Mojeek and Startpage answer automated requests with a
- // challenge; Bing's web RSS with unrelated pages). Then Wikipedia, Hacker
- // News, Bing News and Google News, so one blocked or empty source never
- // means "no results". Each answer must pass the relevance check.
+ // Every engine is free and keyless; no library. Brave and DuckDuckGo are
+ // the real web indexes, and both block some automated requests (by client
+ // fingerprint and rate), so having two, plus DuckDuckGo's lite page, keeps
+ // web search answering. Wikipedia, Hacker News and the news feeds follow.
+ // Bing's web RSS is last: it serves unrelated pages to bots.
+ //
+ // How a search is judged: an engine's answer counts only for the results
+ // that mention the query (relevant()). Engines are asked in order and their
+ // relevant results combined until there are ENOUGH, so one thin or blocked
+ // source never decides the answer. Every engine tried is recorded in the
+ // trail, so "nothing found" and "everything was blocked" read differently.
const engines: Array<[string, (q: string, n: number) => Promise<SearchResult[]>]> = opts.kind === 'news'
- ? [['Google News', googleNews], ['Bing News', bingNews], ['Hacker News', hackerNews]]
- : [['Brave', brave], ['Wikipedia', wikipedia], ['Hacker News', hackerNews], ['Bing News', bingNews], ['Google News', googleNews], ['Bing', bing]];
- const errors: string[] = [];
+ ? [['Bing News', bingNews], ['Google News', googleNews], ['Hacker News', hackerNews]]
+ : [['Brave', brave], ['DuckDuckGo', ddgHtml], ['DuckDuckGo Lite', ddgLite], ['Wikipedia', wikipedia], ['Hacker News', hackerNews], ['Bing News', bingNews], ['Google News', googleNews], ['Bing', bing]];
+ const want = Math.min(ENOUGH, max);
+ const trail: string[] = [];
+ const used: string[] = [];
+ let gathered: SearchResult[] = [];
for (const [name, run] of engines) {
+ // DuckDuckGo Lite is the same index as DuckDuckGo: skip it once that answered.
+ if (name === 'DuckDuckGo Lite' && used.includes('DuckDuckGo')) continue;
try {
const raw = await run(query, max);
- let results = dedupe(relevant(query, raw));
- if (!results.length) { errors.push(`${name}: ${raw.length ? 'only unrelated results' : 'no results'}`); continue; }
- // A thin web answer (a few hits) is topped up with Wikipedia, which
- // is the most reliable second opinion for facts.
- if (opts.kind !== 'news' && results.length < Math.min(4, max) && name !== 'Wikipedia') {
- const extra = relevant(query, await wikipedia(query, max - results.length).catch(() => []));
- if (extra.length) return { results: dedupe([...results, ...extra]).slice(0, max), engine: `${name} + Wikipedia` };
+ const fresh = relevant(query, raw);
+ const before = gathered.length;
+ gathered = dedupe([...gathered, ...fresh]);
+ const added = gathered.length - before;
+ if (!added) {
+ trail.push(`${name}: ${raw.length ? (fresh.length ? 'only duplicates' : 'only unrelated results') : 'no results'}`);
+ continue;
}
- results = results.slice(0, max);
- return { results, engine: name };
- errors.push(`${name}: no results`);
+ used.push(name);
+ trail.push(`${name}: ${added} result${added === 1 ? '' : 's'}`);
+ if (gathered.length >= want) break;
} catch (err) {
- errors.push(`${name}: ${(err as Error).message}`);
+ trail.push(`${name}: ${why(err)}`);
+ }
+ }
+ // The free engines could not answer well: both web indexes blocked us, or
+ // what came back is too thin. Ask the owner's own model provider, which
+ // runs an official search API (a small cost, only on this path).
+ const realIndexAnswered = used.some((n) => n === 'Brave' || n.startsWith('DuckDuckGo'));
+ if (opts.kind !== 'news' && query.trim() && (gathered.length < want || !realIndexAnswered)) {
+ for (const key of opts.providers ?? providerKeys) {
+ const name = key.name === 'anthropic' ? 'Anthropic web search' : 'OpenAI web search';
+ try {
+ const before = gathered.length;
+ // Provider results lead: they come from a real index, the rest were fallbacks.
+ const fromProvider = await providerSearch(key, query, max);
+ gathered = dedupe([...fromProvider, ...gathered]);
+ const added = gathered.length - before;
+ if (!added) { trail.push(`${name}: no results`); continue; }
+ used.unshift(name);
+ trail.push(`${name}: ${added} result${added === 1 ? '' : 's'}`);
+ break;
+ } catch (err) {
+ trail.push(`${name}: ${why(err)}`);
+ }
}
}
- throw new Error(`search failed (${errors.join('; ')})`);
+ if (!gathered.length) throw new Error(`no source found anything (${trail.join('; ')})`);
+ return { results: gathered.slice(0, max), engine: used.join(' + '), trail };
}
export function createWebSearchTool() {
@@ -292,10 +423,10 @@ export function createWebSearchTool() {
})),
execute: async ({ query, kind, max }) => {
try {
- const { results, engine } = await webSearch(query, { kind: kind ?? 'web', max: max ?? 8 });
- return formatResults(results, engine, query, kind ?? 'web');
+ const { results, engine, trail } = await webSearch(query, { kind: kind ?? 'web', max: max ?? 8 });
+ return `${formatResults(results, engine, query, kind ?? 'web')}\n\nSearched: ${trail.join(' → ')}`;
} catch (err) {
- return `Error: web search is unavailable right now: ${(err as Error).message}`;
+ return `Error: web search found nothing: ${(err as Error).message}. Tell the owner which sources were tried and why each failed; try a shorter or rephrased query once.`;
}
},
});
diff --git a/src/index.ts b/src/index.ts
index c8c66c39..ddc501cf 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -4,6 +4,7 @@ import { fileURLToPath } from 'node:url';
import { dirname, join, resolve as pathResolve } from 'node:path';
import { Command } from 'commander';
import { publishStatus, setStatusPublisher } from './core/provider-status.js';
+import { setSearchProviders } from './capabilities/web/web-search.js';
import { loadPermissionMode, savePermissionMode } from './capabilities/permission-mode-store.js';
import chalk from 'chalk';
@@ -3479,6 +3480,12 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
setWebBgTasks(agent.backgroundTasks);
setWebModelSwitch((provider, model) => agent.switchProvider(provider, model));
setWebCurrentProvider(() => agent.getCurrentProvider());
+ // web_search's last resort when the free engines are blocked: the official
+ // search of a provider the owner already configured (Anthropic, then OpenAI).
+ setSearchProviders((['anthropic', 'openai'] as const)
+ .map((name) => config.providers[name])
+ .filter((p) => p && p.enabled && p.apiKey)
+ .map((p) => ({ name: p.name as 'anthropic' | 'openai', apiKey: p.apiKey, baseUrl: p.baseUrl })));
// Live bottom bar for attached terminals and the dashboard: one snapshot,
// pushed on every model switch and checked every 2 s for anything else.
const statusSnapshot = (): Record<string, unknown> => {