Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

⚑️ perf(web-browsing): move crawl error recovery to tool results and slim always-on prompt (#23633)

AmAzing-573b57d8d832
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/webBrowsing.ts b/apps/server/src/services/toolExecution/serverRuntimes/webBrowsing.ts
index a69a8602a13..bb94d3451de 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/webBrowsing.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/webBrowsing.ts
@@ -22,6 +22,7 @@ export const webBrowsingRuntime: ServerRuntimeRegistration = {
return new WebBrowsingExecutionRuntime({
canReadSavedDocuments: !!context.enabledToolIds?.includes(AgentDocumentsIdentifier),
+ canUseBrowserSkill: Boolean(context.deviceCapable),
documentService: canSaveDocuments
? {
associateDocument: async (documentId) => {
diff --git a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.test.ts
index d2d8efe2de9..5d5c24871f8 100644
--- a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.test.ts
+++ b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.test.ts
@@ -262,5 +262,124 @@ describe('WebBrowsingExecutionRuntime', () => {
consoleError.mockRestore();
}
});
+
+ it('appends browser escalation guidance once for multiple retryable failures without mutating state', async () => {
+ const response = {
+ results: [
+ {
+ crawler: 'browserless',
+ data: {
+ content: 'Fail to crawl the page. Error type: TimeoutError, error message: timed out',
+ errorMessage: 'timed out',
+ errorType: 'TimeoutError',
+ },
+ originalUrl: 'https://blocked1.example.com',
+ },
+ {
+ crawler: 'browserless',
+ data: {
+ content: 'Fail to crawl the page. Error type: CrawlError, error message: 403',
+ errorMessage: '403',
+ errorType: 'CrawlError',
+ },
+ originalUrl: 'https://blocked2.example.com',
+ },
+ ],
+ };
+ const runtime = new WebBrowsingExecutionRuntime({
+ canUseBrowserSkill: true,
+ searchService: { crawlPages: vi.fn().mockResolvedValue(response), webSearch: vi.fn() },
+ });
+
+ const result = await runtime.crawlMultiPages({
+ urls: ['https://blocked1.example.com', 'https://blocked2.example.com'],
+ });
+
+ expect(result.content.match(/<guidance>/g)).toHaveLength(1);
+ expect(result.content).toContain('activate the `agent-browser` skill');
+ // Portal UI reads raw `state.results[i].data.content` and must never see model guidance.
+ expect(response.results[0].data.content).not.toContain('agent-browser');
+ expect(response.results[1].data.content).not.toContain('agent-browser');
+ });
+
+ it('omits agent-browser guidance when canUseBrowserSkill is false', async () => {
+ const runtime = new WebBrowsingExecutionRuntime({
+ canUseBrowserSkill: false,
+ searchService: {
+ crawlPages: vi.fn().mockResolvedValue({
+ results: [
+ {
+ crawler: 'browserless',
+ data: {
+ content:
+ 'Fail to crawl the page. Error type: TimeoutError, error message: timeout',
+ errorMessage: 'timeout',
+ errorType: 'TimeoutError',
+ },
+ originalUrl: 'https://blocked.example.com',
+ },
+ ],
+ }),
+ webSearch: vi.fn(),
+ },
+ });
+
+ const result = await runtime.crawlMultiPages({ urls: ['https://blocked.example.com'] });
+
+ expect(result.content).toContain('<guidance>');
+ expect(result.content).not.toContain('agent-browser');
+ expect(result.content).toContain('no browser fallback is available');
+ });
+
+ it('does not append escalation guidance for non-retryable 404 or non-existent domain DNS errors', async () => {
+ const runtime = new WebBrowsingExecutionRuntime({
+ canUseBrowserSkill: true,
+ searchService: {
+ crawlPages: vi.fn().mockResolvedValue({
+ results: [
+ {
+ crawler: 'naive',
+ data: {
+ content: 'Dead link (HTTP 404)',
+ errorMessage: 'Not Found',
+ errorType: 'PageNotFoundError',
+ retryable: false,
+ },
+ originalUrl: 'https://example.com/missing',
+ },
+ {
+ crawler: 'naive',
+ data: {
+ content:
+ 'Fail to crawl the page. Error type: NetworkConnectionError, error message: getaddrinfo ENOTFOUND nope.invalid',
+ errorMessage: 'getaddrinfo ENOTFOUND nope.invalid',
+ errorType: 'NetworkConnectionError',
+ },
+ originalUrl: 'https://nope.invalid/',
+ },
+ {
+ crawler: 'search1api',
+ data: {
+ content:
+ 'Fail to crawl the page. Error type: HTTPStatusError, error message: Failed to crawl URL: Domain does not exist: www.nope.invalid (DNS NXDOMAIN)',
+ errorMessage:
+ 'Failed to crawl URL: Domain does not exist: www.nope.invalid (DNS NXDOMAIN)',
+ errorType: 'HTTPStatusError',
+ },
+ originalUrl: 'https://www.nope.invalid/',
+ },
+ ],
+ }),
+ webSearch: vi.fn(),
+ },
+ });
+
+ const result = await runtime.crawlMultiPages({
+ urls: ['https://example.com/missing', 'https://nope.invalid/'],
+ });
+
+ expect(result.content).not.toContain('<guidance>');
+ expect(result.content).not.toContain('agent-browser');
+ });
});
});
diff --git a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts
index d624ce106d0..7f0d78bd560 100644
--- a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts
@@ -54,6 +54,36 @@ export interface WebBrowsingDocumentService {
}) => Promise<{ id: string }>;
}
+const NON_ESCALATABLE_ERROR_TYPES = new Set([
+ 'InvalidUrlError',
+ 'PageNotFoundError',
+ 'UnsupportedContentError',
+]);
+
+const NON_EXISTENT_DOMAIN_RE =
+ /\b(?:ENOTFOUND|ERR_NAME_NOT_RESOLVED|EAI_NONAME|NXDOMAIN)\b|domain does not exist/i;
+
+const isEscalatableCrawlError = (data: Record<string, any>): boolean => {
+ if (!('errorMessage' in data)) return false;
+ if (data.retryable === false) return false;
+ if (typeof data.errorType === 'string' && NON_ESCALATABLE_ERROR_TYPES.has(data.errorType)) {
+ return false;
+ }
+ const detail = `${data.errorMessage ?? ''} ${data.content ?? ''}`;
+ if (NON_EXISTENT_DOMAIN_RE.test(detail)) return false;
+ return true;
+};
+
+const formatCrawlFailureGuidance = (canUseBrowserSkill: boolean | undefined): string => {
+ if (canUseBrowserSkill === true) {
+ return '<guidance>Do not keep retrying failed crawls with different queries or sources β€” activate the `agent-browser` skill and re-fetch with a real browser (anti-bot walls often masquerade as timeouts or generic errors).</guidance>';
+ }
+ if (canUseBrowserSkill === false) {
+ return '<guidance>Do not keep retrying failed crawls with the same URL β€” no browser fallback is available in this environment; try a different source or explain the crawl failure to the user.</guidance>';
+ }
+ return '<guidance>Do not keep retrying failed crawls β€” if the `agent-browser` skill is available, activate it and re-fetch with a real browser (anti-bot walls often masquerade as timeouts or generic errors); otherwise try another source or explain the failure.</guidance>';
+};
+
export interface WebBrowsingRuntimeOptions {
agentId?: string;
/**
@@ -62,6 +92,12 @@ export interface WebBrowsingRuntimeOptions {
* tool set with browsing alone still saves the page but reports what was left out instead.
*/
canReadSavedDocuments?: boolean;
+ /**
+ * Whether a device-capable browser fallback (`agent-browser` skill) is available in this run.
+ * When `false`, crawl-failure guidance omits `agent-browser` so the model does not hunt for
+ * an unavailable skill; when `undefined`, uses conditional phrasing.
+ */
+ canUseBrowserSkill?: boolean;
documentService?: WebBrowsingDocumentService;
searchService: SearchServiceImpl;
topicId?: string;
@@ -70,6 +106,7 @@ export interface WebBrowsingRuntimeOptions {
export class WebBrowsingExecutionRuntime {
private agentId?: string;
private canReadSavedDocuments: boolean;
+ private canUseBrowserSkill?: boolean;
private documentService?: WebBrowsingDocumentService;
private searchService: SearchServiceImpl;
private topicId?: string;
@@ -78,6 +115,7 @@ export class WebBrowsingExecutionRuntime {
this.searchService = options.searchService;
this.documentService = options.documentService;
this.canReadSavedDocuments = options.canReadSavedDocuments ?? false;
+ this.canUseBrowserSkill = options.canUseBrowserSkill;
this.agentId = options.agentId;
this.topicId = options.topicId;
}
@@ -193,9 +231,13 @@ export class WebBrowsingExecutionRuntime {
};
});
const xmlContent = crawlResultsPrompt(content as any);
+ const hasEscalatableError = results.some((item) => isEscalatableCrawlError(item.data as any));
+ const finalContent = hasEscalatableError
+ ? `${xmlContent}\n${formatCrawlFailureGuidance(this.canUseBrowserSkill)}`
+ : xmlContent;
return {
- content: xmlContent,
+ content: finalContent,
state: response,
success: true,
};
diff --git a/packages/builtin-tool-web-browsing/src/manifest.ts b/packages/builtin-tool-web-browsing/src/manifest.ts
index bb9796e1973..f2be8fcd334 100644
--- a/packages/builtin-tool-web-browsing/src/manifest.ts
+++ b/packages/builtin-tool-web-browsing/src/manifest.ts
@@ -6,17 +6,16 @@ import { WebBrowsingApiName } from './types';
export const WebBrowsingManifest: BuiltinToolManifest = {
api: [
{
- description:
- 'a search service with automatic engine selection. Useful for when you need to answer questions about current events. Input should be a search query. Output is a JSON array of the query results. An empty result is a completed search, not an error: never resend the same query β€” rewrite it instead (fewer quoted phrases, no site:/language modifiers, more general keywords).',
+ description: 'Search the web with automatic engine selection.',
name: WebBrowsingApiName.search,
parameters: {
properties: {
query: {
- description: 'The search query',
+ description: 'Search query',
type: 'string',
},
searchCategories: {
- description: 'The search categories you can set:',
+ description: 'Optional categories',
items: {
enum: ['general', 'images', 'news', 'science', 'videos'],
type: 'string',
@@ -24,7 +23,7 @@ export const WebBrowsingManifest: BuiltinToolManifest = {
type: 'array',
},
searchTimeRange: {
- description: 'The time range you can set:',
+ description: 'Optional time range',
enum: ['anytime', 'day', 'week', 'month', 'year'],
type: 'string',
},
@@ -34,14 +33,12 @@ export const WebBrowsingManifest: BuiltinToolManifest = {
},
},
{
- description:
- 'A crawler can visit page content. Output is a JSON object of title, content, url and website. Only pass absolute http(s) URLs of HTML/text document pages; image, SVG, font, video and archive files have no readable content. A 404/410 dead-link result is final β€” do not retry it.',
+ description: 'Crawl one absolute http(s) HTML/text webpage URL.',
name: WebBrowsingApiName.crawlSinglePage,
parameters: {
properties: {
url: {
- description:
- 'The absolute http(s) URL to crawl, e.g. https://example.com/path β€” not a bare domain, markdown link or free text',
+ description: 'Absolute http(s) URL to crawl',
type: 'string',
},
},
@@ -50,15 +47,13 @@ export const WebBrowsingManifest: BuiltinToolManifest = {
},
},
{
- description:
- 'A crawler can visit multi pages. If need to visit multi website, use this one. Output is an array of JSON object of title, content, url and website. Only pass absolute http(s) URLs of HTML/text document pages; image, SVG, font, video and archive files have no readable content. A 404/410 dead-link result is final β€” do not retry it.',
+ description: 'Crawl multiple absolute http(s) HTML/text webpage URLs.',
name: WebBrowsingApiName.crawlMultiPages,
parameters: {
properties: {
urls: {
items: {
- description:
- 'An absolute http(s) URL to crawl, e.g. https://example.com/path β€” not a bare domain, markdown link or free text',
+ description: 'Absolute http(s) URL to crawl',
type: 'string',
},
type: 'array',
diff --git a/packages/builtin-tool-web-browsing/src/systemRole.test.ts b/packages/builtin-tool-web-browsing/src/systemRole.test.ts
index 21e7730eec5..c993db1c464 100644
--- a/packages/builtin-tool-web-browsing/src/systemRole.test.ts
+++ b/packages/builtin-tool-web-browsing/src/systemRole.test.ts
@@ -6,34 +6,38 @@ describe('web browsing systemPrompt', () => {
const prompt = systemPrompt();
it('keeps the time range opt-in for time-sensitive queries', () => {
- expect(prompt).toContain('Set `searchTimeRange` only for time-sensitive queries');
+ expect(prompt).toContain('set `searchTimeRange` only for time-sensitive queries');
expect(prompt).not.toMatch(/Default to[^;\n]*`searchTimeRange`/);
});
it('balances "a few authoritative sources" with cross-checking', () => {
- expect(prompt).toContain('Verify key facts across multiple sources');
- expect(prompt).toContain('sources representing different perspectives');
+ expect(prompt).toContain('verify key facts across sources');
+ expect(prompt).toContain('perspectives for controversial topics');
});
- it('escalates every crawl failure to a real browser, not only recognised blocks', () => {
- expect(prompt).toContain('If a crawl fails (error, timeout, blocked)');
- expect(prompt).toContain('do NOT keep retrying with different queries or sources');
- expect(prompt).toContain('activate the `agent-browser` skill');
- expect(prompt).toContain('When in doubt, escalate');
+ it('keeps engine auto-selection and avoids ambiguous !category placeholder', () => {
+ expect(prompt).toContain('let search choose engines automatically unless asked');
+ expect(prompt).not.toContain('!category');
});
- it('skips browser escalation only for definitively dead links', () => {
- expect(prompt).toContain('definitively dead links (HTTP 404/410, non-existent domain)');
+ it('preserves URL and ambiguous-query guardrails from #18702 and #23595', () => {
+ expect(prompt).toContain('Clarify ambiguous queries before extensive searching');
+ expect(prompt).toContain(
+ 'never bare domains, markdown links, guessed paths, or non-HTML assets',
+ );
});
- it('gives each non-retryable crawl error the remedy its tool result gives', () => {
- const line = prompt.split('\n').find((item) => item.includes('`PageNotFoundError`'));
- const [deadLink, nothingFetched] = line!.split('`InvalidUrlError`');
+ it('escalates failed or challenge/JS-wall crawls to agent-browser', () => {
+ expect(prompt).toContain('If a crawl fails or returns an empty');
+ expect(prompt).toContain('activate the `agent-browser` skill');
+ });
- expect(deadLink).toContain('search for a different source');
- expect(deadLink).not.toContain('fix the URL');
- expect(nothingFetched).toContain('`UnsupportedContentError`');
- expect(nothingFetched).toContain('fix the URL or pick a document page');
+ it('keeps error-specific recovery essays out of the always-on system prompt', () => {
+ // Empty-search and crawl-error remedies travel on the error tool results themselves.
+ expect(prompt).not.toContain('PageNotFoundError');
+ expect(prompt).not.toContain('InvalidUrlError');
+ expect(prompt).not.toContain('UnsupportedContentError');
+ expect(prompt.length).toBeLessThan(1400);
});
it('shows the footnote citation as renderable markdown, not inline code', () => {
diff --git a/packages/builtin-tool-web-browsing/src/systemRole.ts b/packages/builtin-tool-web-browsing/src/systemRole.ts
index c7cd5852d4c..a48397746cd 100644
--- a/packages/builtin-tool-web-browsing/src/systemRole.ts
+++ b/packages/builtin-tool-web-browsing/src/systemRole.ts
@@ -1,32 +1,13 @@
export const systemPrompt = (
_date?: string,
-) => `Use Web Browsing to search the internet and crawl webpages for accurate, up-to-date answers.
+) => `Use Web Browsing to search the internet and crawl webpages for up-to-date answers.
-<search_guidelines>
-- Default to plain queries with \`searchCategories\` (e.g. \`general\`); let the metasearch service choose engines automatically unless the user asks to test a specific engine. Set \`searchTimeRange\` only for time-sensitive queries.
-- Optional query modifiers (use sparingly at query start): \`!category\` (\`!general\`, \`!news\`, \`!science\`, \`!it\`, \`!images\`, \`!videos\`, \`!map\`, \`!files\`, \`!social_media\`), \`:lang\` (e.g. \`:fr\`), and \`site:domain.com\`.
-- Prefer a few authoritative sources over broad category combinations; use \`crawlSinglePage\` for one page or \`crawlMultiPages\` for multiple pages.
-- Verify key facts across multiple sources when possible; for controversial topics, crawl sources representing different perspectives.
-</search_guidelines>
+- Default to plain queries and let search choose engines automatically unless asked; set \`searchTimeRange\` only for time-sensitive queries. Optional modifiers: \`:lang\`, \`site:domain.com\`.
+- Clarify ambiguous queries before extensive searching.
+- Prefer a few authoritative sources, verify key facts across sources (and perspectives for controversial topics), and pass only seen absolute \`http(s)\` URLs of publicly accessible HTML/text pages to \`crawlSinglePage\` / \`crawlMultiPages\` (never bare domains, markdown links, guessed paths, or non-HTML assets like images/SVG/fonts/video/archives).
+- If a crawl fails or returns an empty, verification, challenge, or JS-wall body, activate the \`agent-browser\` skill when available instead of retrying.
+- Cite sources with markdown footnotes, list all referenced URLs at the end, and note retrieval date / flag potentially outdated sources for time-sensitive facts:
+ Claim[^1].
-<crawling_guidelines>
-- Pass exact absolute \`http(s)\` URLs you have actually seen linked (never bare domains, markdown links, free text, guessed file/release paths, or non-HTML assets like images/SVG/icons/fonts/video/audio/archives). Only crawl publicly accessible HTML/text pages.
-</crawling_guidelines>
-
-<citations>
-- Cite web sources with markdown footnotes and list all referenced URLs at the end:
- <example>
- Global temperatures have risen by 1.1Β°C since pre-industrial times[^1].
-
- [^1]: [Climate Report 2023](https://example.org/climate-report-2023)
- </example>
-- Note retrieval date for time-sensitive facts and flag potentially outdated sources.
-</citations>
-
-<error_handling>
-- **Empty search result**: Completed search, not a transient error β€” NEVER resend the same query unchanged. Rewrite with fewer/more general keywords, drop quoted phrases, remove \`site:\`/language modifiers, widen/remove time range, try another category, or retry in English for technical/scientific queries. Stop after 2–3 rewrites and tell the user.
-- **Crawl errors that retrying won't fix**: \`PageNotFoundError\` (HTTP 404/410) is the server's authoritative answer that the page does not exist β€” do not retry that URL or try variants of a guessed path; search for a different source. \`InvalidUrlError\` and \`UnsupportedContentError\` mean nothing was fetched β€” fix the URL or pick a document page rather than resending the same one.
-- **Crawl failures & browser escalation**: If a crawl fails (error, timeout, blocked) or returns an empty/verification/challenge/obfuscated-JS body, do NOT keep retrying with different queries or sources β€” activate the \`agent-browser\` skill when available and re-fetch the page with it. Exception: skip escalation for definitively dead links (HTTP 404/410, non-existent domain) and try a different source instead. When in doubt, escalate: anti-bot walls often masquerade as timeouts or generic errors. Only when no browser path exists, explain the issue and suggest alternatives.
-- **Ambiguous queries**: Clarify or suggest interpretations before extensive searching.
-</error_handling>
+ [^1]: [Source](https://example.org)
`;
diff --git a/packages/prompts/src/prompts/search/searchResults.test.ts b/packages/prompts/src/prompts/search/searchResults.test.ts
index d2b77bc0704..24aa2b4ad7f 100644
--- a/packages/prompts/src/prompts/search/searchResults.test.ts
+++ b/packages/prompts/src/prompts/search/searchResults.test.ts
@@ -8,6 +8,8 @@ describe('searchResultsPrompt', () => {
expect(result).toBe(EMPTY_SEARCH_RESULTS_PROMPT);
expect(result).toContain('No results found.');
expect(result).toContain('do not resend the same query');
+ expect(result).toContain('retry in English');
+ expect(result).toContain('Stop after 2–3 rewrites');
});
it('should convert basic search results to compact XML format', () => {
diff --git a/packages/prompts/src/prompts/search/searchResults.ts b/packages/prompts/src/prompts/search/searchResults.ts
index f7f4a91113c..67bbacb2f3d 100644
--- a/packages/prompts/src/prompts/search/searchResults.ts
+++ b/packages/prompts/src/prompts/search/searchResults.ts
@@ -14,7 +14,7 @@ export interface SearchResultItem {
* Say so explicitly: models otherwise re-issue the identical (billed) query.
*/
export const EMPTY_SEARCH_RESULTS_PROMPT =
- '<searchResults>No results found. The search completed successfully and this is the final answer for this exact query β€” do not resend the same query. To find something, rewrite it: drop or reduce quoted phrases, remove site:/language modifiers, widen the time range, or use fewer, more general keywords.</searchResults>';
+ '<searchResults>No results found. The search completed successfully and this is the final answer for this exact query β€” do not resend the same query. To find something, rewrite it: drop or reduce quoted phrases, remove site:/language modifiers, widen the time range, try another category, use fewer/more general keywords, or retry in English for technical/scientific queries. Stop after 2–3 rewrites and tell the user.</searchResults>';
/**
* Convert search results array to compact XML format for token efficiency