Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(search): tools only, no model-provider search; retry DuckDuckGo challenge
Salman Qureshi50c249a037c0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b2c8565e..c9454205 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,8 +4,8 @@### 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.+- **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, retries a DuckDuckGo challenge once after a short pause, and combines relevant results until it has enough, instead of stopping at the first engine with one hit.+- **Search never depends on the model.** Results come only from Mercury's own search tools, never from a provider's built-in web search, so search works the same with every model.- **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 againdiff --git a/src/capabilities/web/provider-search.ts b/src/capabilities/web/provider-search.tsdeleted file mode 100644index 42c0838c..00000000--- a/src/capabilities/web/provider-search.ts+++ /dev/null@@ -1,99 +0,0 @@-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.tsindex 365dd8a6..60f856af 100644--- a/src/capabilities/web/web-search.test.ts+++ b/src/capabilities/web/web-search.test.ts@@ -192,44 +192,19 @@ describe('web_search', () => {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;- }+++ it('a DuckDuckGo challenge is retried once after a short pause', async () => {+ const page = `<a class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.dev%2Fcanberra">Canberra guide</a><a class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.dev%2Fcanberra2">Visit Canberra</a><a class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.dev%2Fcanberra3">Canberra history</a><a class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.dev%2Fcanberra4">Canberra map</a>`;+ let ddgCalls = 0;+ vi.mocked(guardedFetch).mockImplementation((async (url: string) => {+ if (url.includes('search.brave.com')) return new Response('', { status: 429 });+ if (url.includes('html.duckduckgo.com')) return ++ddgCalls === 1 ? new Response('<html>anomaly</html>', { status: 202 }) : new Response(page, { status: 200 });+ return new Response('', { status: 404 });+ }) as never);+ const r = await webSearch('canberra');+ expect(ddgCalls).toBe(2);+ expect(r.engine).toBe('DuckDuckGo');+ expect(r.trail).toEqual(['Brave: blocked (HTTP 429)', 'DuckDuckGo: 4 results']);});});diff --git a/src/capabilities/web/web-search.ts b/src/capabilities/web/web-search.tsindex 8101b1d7..e58f1ca8 100644--- a/src/capabilities/web/web-search.ts+++ b/src/capabilities/web/web-search.ts@@ -1,7 +1,6 @@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.@@ -172,8 +171,10 @@ export function parseDdg(html: string, max: number): SearchResult[] {return out;}-async function ddg(kind: 'html' | 'lite', query: string, max: number): Promise<SearchResult[]> {- if (!query.trim()) return [];+/** DuckDuckGo lets roughly every other automated request through: one retry after a short pause. */+const DDG_RETRY_MS = 1500;++async function ddgOnce(kind: 'html' | 'lite', query: string, max: number): Promise<SearchResult[]> {const ac = new AbortController();const timer = setTimeout(() => ac.abort(), TIMEOUT_MS);try {@@ -186,6 +187,17 @@ async function ddg(kind: 'html' | 'lite', query: string, max: number): Promise<SclearTimeout(timer);}}++async function ddg(kind: 'html' | 'lite', query: string, max: number): Promise<SearchResult[]> {+ if (!query.trim()) return [];+ try {+ return await ddgOnce(kind, query, max);+ } catch (err) {+ if (!/challenge/.test((err as Error).message)) throw err;+ await new Promise((r) => setTimeout(r, DDG_RETRY_MS));+ return ddgOnce(kind, query, max);+ }+}const ddgHtml = (q: string, n: number) => ddg('html', q, n);const ddgLite = (q: string, n: number) => ddg('lite', q, n);@@ -334,16 +346,7 @@ function why(err: unknown): string {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> {+export async function webSearch(query: string, opts: { kind?: 'web' | 'news'; max?: number } = {}): Promise<SearchOutcome> {const max = Math.max(1, Math.min(opts.max ?? 8, 15));// Every engine is free and keyless; no library. Brave and DuckDuckGo are// the real web indexes, and both block some automated requests (by client@@ -383,28 +386,6 @@ export async function webSearch(query: string, opts: { kind?: 'web' | 'news'; matrail.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)}`);- }- }- }if (!gathered.length) throw new Error(`no source found anything (${trail.join('; ')})`);return { results: gathered.slice(0, max), engine: used.join(' + '), trail };}diff --git a/src/index.ts b/src/index.tsindex ddc501cf..c8c66c39 100644--- a/src/index.ts+++ b/src/index.ts@@ -4,7 +4,6 @@ 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';@@ -3480,12 +3479,6 @@ 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> => {