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.

πŸ› fix(web-browsing): stop paying for invalid and unretryable crawl/search calls (#18702)

Arvin Xube3d4c53d5df
diff --git a/apps/server/src/services/search/index.test.ts b/apps/server/src/services/search/index.test.ts
index 33dfc715425..3b2ca986c98 100644
--- a/apps/server/src/services/search/index.test.ts
+++ b/apps/server/src/services/search/index.test.ts
@@ -672,6 +672,32 @@ describe('SearchService', () => {
expect(result.results[0]).toBe(failedResult);
});
+ it('should not retry a failed result the crawler marked non-retryable (dead link / invalid url)', async () => {
+ vi.mocked(toolsEnv).CRAWLER_RETRY = 3;
+
+ const deadLink = {
+ crawler: 'search1api',
+ data: {
+ content: 'Dead link: the server confirmed this page does not exist (HTTP 404).',
+ errorMessage: 'Not Found',
+ errorType: 'PageNotFoundError',
+ retryable: false,
+ },
+ originalUrl: 'https://raw.githubusercontent.com/foo/bar/main/env.release',
+ };
+
+ const mockCrawler = {
+ crawl: vi.fn().mockResolvedValue(deadLink),
+ };
+ vi.mocked(Crawler).mockImplementation(() => mockCrawler as any);
+
+ searchService = new SearchService();
+ const result = await searchService.crawlPages({ urls: [deadLink.originalUrl] });
+
+ expect(mockCrawler.crawl).toHaveBeenCalledTimes(1);
+ expect(result.results[0]).toBe(deadLink);
+ });
+
it('should not retry when CRAWLER_RETRY is 0', async () => {
vi.mocked(toolsEnv).CRAWLER_RETRY = 0;
diff --git a/apps/server/src/services/search/index.ts b/apps/server/src/services/search/index.ts
index f443eb62c89..5fb128a62bf 100644
--- a/apps/server/src/services/search/index.ts
+++ b/apps/server/src/services/search/index.ts
@@ -127,6 +127,12 @@ export class SearchService {
if (!this.isFailedCrawlResult(result)) {
return result;
}
+
+ // Dead link / invalid URL / resource file / rejected request: a retry is the
+ // same billed request with the same authoritative answer.
+ if (!this.isRetryableCrawlResult(result)) {
+ return result;
+ }
} catch (error) {
lastError = error as Error;
}
@@ -155,6 +161,10 @@ export class SearchService {
return !('contentType' in result.data);
}
+ private isRetryableCrawlResult(result: CrawlUniformResult): boolean {
+ return !('retryable' in result.data) || result.data.retryable !== false;
+ }
+
private get searchImpls() {
return parseImplEnv(toolsEnv.SEARCH_PROVIDERS) as SearchImplType[];
}
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 6f07d76e612..a2399d39372 100644
--- a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.test.ts
+++ b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.test.ts
@@ -1,3 +1,4 @@
+import { EMPTY_SEARCH_RESULTS_PROMPT } from '@lobechat/prompts';
import { describe, expect, it, vi } from 'vitest';
import { WebBrowsingExecutionRuntime } from './index';
@@ -67,7 +68,8 @@ describe('WebBrowsingExecutionRuntime', () => {
const result = await runtime.search({ query: 'test' });
expect(result.success).toBe(true);
- expect(result.content).toBe('<searchResults />');
+ expect(result.content).toBe(EMPTY_SEARCH_RESULTS_PROMPT);
+ expect(result.content).toContain('do not resend the same query');
});
it('should return success: false when webSearch throws', async () => {
@@ -83,4 +85,51 @@ describe('WebBrowsingExecutionRuntime', () => {
expect(result.content).toBe('Network error');
});
});
+
+ describe('crawlMultiPages', () => {
+ it('should keep the failing url and guidance visible for error items', async () => {
+ const mockSearchService = {
+ crawlPages: vi.fn().mockResolvedValue({
+ results: [
+ {
+ crawler: 'naive',
+ data: {
+ content: 'x'.repeat(20),
+ contentType: 'text',
+ title: 'OK page',
+ url: 'https://ok.example.com/',
+ },
+ originalUrl: 'https://ok.example.com/',
+ },
+ {
+ crawler: 'search1api',
+ data: {
+ content:
+ 'Dead link: the server confirmed this page does not exist (HTTP 404). Do not retry this URL.',
+ errorMessage: 'Not Found',
+ errorType: 'PageNotFoundError',
+ retryable: false,
+ },
+ originalUrl: 'https://raw.githubusercontent.com/foo/bar/main/env.release',
+ },
+ ],
+ }),
+ webSearch: vi.fn(),
+ };
+
+ const runtime = new WebBrowsingExecutionRuntime({ searchService: mockSearchService });
+ const result = await runtime.crawlMultiPages({
+ urls: [
+ 'https://ok.example.com/',
+ 'https://raw.githubusercontent.com/foo/bar/main/env.release',
+ ],
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('<page url="https://ok.example.com/" title="OK page"');
+ expect(result.content).toContain(
+ '<error errorType="PageNotFoundError" errorMessage="Not Found" url="https://raw.githubusercontent.com/foo/bar/main/env.release">Dead link: the server confirmed this page does not exist (HTTP 404). Do not retry this URL.</error>',
+ );
+ });
+ });
});
diff --git a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts
index d6a073d6372..21f560fc293 100644
--- a/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-web-browsing/src/ExecutionRuntime/index.ts
@@ -116,8 +116,9 @@ export class WebBrowsingExecutionRuntime {
}
const content = results.map((item) =>
- 'errorMessage' in item
- ? item
+ 'errorMessage' in item.data
+ ? // keep the failing url attached so the model knows which page to give up on
+ { ...item.data, url: item.data.url ?? item.originalUrl }
: {
...item.data,
// if crawl too many content
diff --git a/packages/builtin-tool-web-browsing/src/manifest.ts b/packages/builtin-tool-web-browsing/src/manifest.ts
index 01daa632e78..22ad1232127 100644
--- a/packages/builtin-tool-web-browsing/src/manifest.ts
+++ b/packages/builtin-tool-web-browsing/src/manifest.ts
@@ -8,7 +8,7 @@ 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',
+ '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).',
name: WebBrowsingApiName.search,
parameters: {
properties: {
@@ -36,12 +36,13 @@ export const WebBrowsingManifest: BuiltinToolManifest = {
},
{
description:
- 'A crawler can visit page content. Output is a JSON object of title, content, url and website',
+ '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.',
name: WebBrowsingApiName.crawlSinglePage,
parameters: {
properties: {
url: {
- description: 'The url need to be crawled',
+ description:
+ 'The absolute http(s) URL to crawl, e.g. https://example.com/path β€” not a bare domain, markdown link or free text',
type: 'string',
},
},
@@ -51,13 +52,14 @@ 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',
+ '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.',
name: WebBrowsingApiName.crawlMultiPages,
parameters: {
properties: {
urls: {
items: {
- description: 'The urls need to be crawled',
+ description:
+ 'An absolute http(s) URL to crawl, e.g. https://example.com/path β€” not a bare domain, markdown link or free text',
type: 'string',
},
type: 'array',
diff --git a/packages/builtin-tool-web-browsing/src/systemRole.ts b/packages/builtin-tool-web-browsing/src/systemRole.ts
index e3e7025cb02..ca62809379a 100644
--- a/packages/builtin-tool-web-browsing/src/systemRole.ts
+++ b/packages/builtin-tool-web-browsing/src/systemRole.ts
@@ -100,6 +100,8 @@ Our search service is a metasearch engine with automatic engine selection. Provi
</search_service_description>
<crawling_best_practices>
+- Pass absolute http(s) URLs exactly as they appear in search results (https://example.com/path). Never pass bare domains, markdown links, or free text as a URL.
+- Only crawl HTML/text document pages. Images, SVG, icons, fonts, video/audio and archives have no readable body and are rejected. Do not guess file paths (e.g. raw.githubusercontent.com/.../env.release or a release tag) β€” crawl a page you have actually seen linked.
- Only crawl pages that are publicly accessible
- When crawling multiple pages, crawl relevant and authoritative sources
- Prioritize authoritative sources over user-generated content when appropriate
@@ -109,11 +111,12 @@ Our search service is a metasearch engine with automatic engine selection. Provi
</crawling_best_practices>
<error_handling>
-- If a search returns poor or no results:
- 1. Analyze the query and results. Could the query be improved (more specific, different keywords)?
+- A search that returns no results is a completed search with a final answer, not a transient error. NEVER resend the same query unchanged β€” every repeat costs the same and returns the same "nothing". Instead:
+ 1. Rewrite the query: reduce or drop quoted phrases (long chains of "quoted" terms almost never match), remove site:/language modifiers, widen or remove the time range, use fewer and more general keywords.
2. Consider trying alternative categories or query terms.
3. If the search was language-specific and failed (especially for technical, scientific, or non-regional topics), try rewriting the query or searching again using English.
- 4. If needed, explain the issue to the user and suggest alternative search terms or strategies.
+ 4. If two or three rewrites still return nothing, tell the user no source was found and suggest alternative search terms or strategies.
+- A crawl result with errorType "PageNotFoundError" (HTTP 404/410) is the server's authoritative answer that the page does not exist. Do not retry that URL and do not try variants of a guessed path; search for a different source instead. Likewise "InvalidUrlError" and "UnsupportedContentError" mean nothing was fetched β€” fix the URL or pick a document page rather than retrying.
- If a crawl fails (error, timeout, blocked) or returns an empty body, a verification/challenge page, or mostly obfuscated JavaScript, the page needs a real browser β€” do NOT keep retrying with different queries or sources. When the agent-browser skill is available, activate it and re-fetch the page with it. Exception: a definitively dead link (HTTP 404/410, non-existent domain) won't open in a browser either β€” skip escalation and try a different source. When in doubt, escalate: anti-bot walls often masquerade as timeouts or generic errors. Only when no browser path exists, explain the issue to the user and suggest alternatives (e.g., trying a different source from search results).
- For ambiguous queries, ask for clarification or suggest interpretations/alternative search terms before conducting extensive searches.
- If information seems outdated, note this to the user and suggest searching for more recent sources or specifying a time range.
diff --git a/packages/builtin-tool-web-browsing/vitest.config.mts b/packages/builtin-tool-web-browsing/vitest.config.mts
new file mode 100644
index 00000000000..9e935ef21d1
--- /dev/null
+++ b/packages/builtin-tool-web-browsing/vitest.config.mts
@@ -0,0 +1,18 @@
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { defineConfig } from 'vitest/config';
+
+const packageDir = path.dirname(fileURLToPath(import.meta.url));
+const repoRoot = path.resolve(packageDir, '../..');
+
+export default defineConfig({
+ resolve: {
+ alias: {
+ '@': path.resolve(repoRoot, 'src'),
+ },
+ },
+ test: {
+ environment: 'happy-dom',
+ },
+});
diff --git a/packages/prompts/src/prompts/search/crawlResults.test.ts b/packages/prompts/src/prompts/search/crawlResults.test.ts
index 2c9c6eb5116..53b8b4ee78e 100644
--- a/packages/prompts/src/prompts/search/crawlResults.test.ts
+++ b/packages/prompts/src/prompts/search/crawlResults.test.ts
@@ -135,6 +135,24 @@ describe('crawlResultsPrompt', () => {
</crawlResults>`);
});
+ it('should render error guidance content as element text', () => {
+ const results = [
+ {
+ content:
+ 'Dead link: the server confirmed this page does not exist (HTTP 404). Do not retry this URL.',
+ errorMessage: 'Not Found',
+ errorType: 'PageNotFoundError',
+ url: 'https://raw.githubusercontent.com/foo/bar/main/env.release',
+ },
+ ];
+
+ const xml = crawlResultsPrompt(results);
+
+ expect(xml).toEqual(`<crawlResults>
+ <error errorType="PageNotFoundError" errorMessage="Not Found" url="https://raw.githubusercontent.com/foo/bar/main/env.release">Dead link: the server confirmed this page does not exist (HTTP 404). Do not retry this URL.</error>
+</crawlResults>`);
+ });
+
it('should handle error without url', () => {
const results = [
{
diff --git a/packages/prompts/src/prompts/search/crawlResults.ts b/packages/prompts/src/prompts/search/crawlResults.ts
index 250b7ac2cd1..add7125209a 100644
--- a/packages/prompts/src/prompts/search/crawlResults.ts
+++ b/packages/prompts/src/prompts/search/crawlResults.ts
@@ -49,7 +49,13 @@ export const crawlResultsPrompt = (results: Array<CrawlResultItem | CrawlErrorIt
attrs.push(`url="${escapeXmlAttr(item.url)}"`);
}
- return ` <error ${attrs.join(' ')} />`;
+ // The crawler puts model-facing guidance in `content` (e.g. "dead link, do not
+ // retry"); keep it visible instead of collapsing the error to two attributes.
+ const guidance = item.content ? escapeXmlContent(item.content) : '';
+
+ return guidance
+ ? ` <error ${attrs.join(' ')}>${guidance}</error>`
+ : ` <error ${attrs.join(' ')} />`;
}
// Handle successful crawl items
diff --git a/packages/prompts/src/prompts/search/searchResults.test.ts b/packages/prompts/src/prompts/search/searchResults.test.ts
index 8eedb8cb554..d2b77bc0704 100644
--- a/packages/prompts/src/prompts/search/searchResults.test.ts
+++ b/packages/prompts/src/prompts/search/searchResults.test.ts
@@ -1,11 +1,13 @@
import { describe, expect, it } from 'vitest';
-import { searchResultsPrompt } from './searchResults';
+import { EMPTY_SEARCH_RESULTS_PROMPT, searchResultsPrompt } from './searchResults';
describe('searchResultsPrompt', () => {
it('should return explicit empty message for empty results', () => {
const result = searchResultsPrompt([]);
- expect(result).toBe('<searchResults>No results found.</searchResults>');
+ expect(result).toBe(EMPTY_SEARCH_RESULTS_PROMPT);
+ expect(result).toContain('No results found.');
+ expect(result).toContain('do not resend the same query');
});
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 08138f12cf6..f7f4a91113c 100644
--- a/packages/prompts/src/prompts/search/searchResults.ts
+++ b/packages/prompts/src/prompts/search/searchResults.ts
@@ -9,6 +9,13 @@ export interface SearchResultItem {
url: string;
}
+/**
+ * A completed search with zero hits is a final answer, not a transient failure.
+ * 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>';
+
/**
* Convert search results array to compact XML format for token efficiency
* Uses attributes for title/url and element content for main text
@@ -26,7 +33,7 @@ export interface SearchResultItem {
* ```
*/
export const searchResultsPrompt = (results: SearchResultItem[]): string => {
- if (results.length === 0) return '<searchResults>No results found.</searchResults>';
+ if (results.length === 0) return EMPTY_SEARCH_RESULTS_PROMPT;
const items = results
.map((item) => {
diff --git a/packages/web-crawler/src/__tests__/crawler.test.ts b/packages/web-crawler/src/__tests__/crawler.test.ts
index 3cbea2c96f6..9db63bb221b 100644
--- a/packages/web-crawler/src/__tests__/crawler.test.ts
+++ b/packages/web-crawler/src/__tests__/crawler.test.ts
@@ -1,12 +1,14 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { Crawler } from '../crawler';
+import { HTTPStatusError, PageNotFoundError } from '../utils/errorType';
// Move mocks outside of test cases to avoid hoisting issues
vi.mock('../crawImpl', () => ({
crawlImpls: {
naive: vi.fn(),
jina: vi.fn(),
+ search1api: vi.fn(),
browserless: vi.fn(),
},
}));
@@ -246,4 +248,132 @@ describe('Crawler', () => {
transformedUrl: undefined,
});
});
+
+ describe('preflight', () => {
+ it('should reject an invalid url without calling any impl', async () => {
+ const { crawlImpls } = await import('../crawImpl');
+
+ const result = await crawler.crawl({ url: 'not a url at all' });
+
+ expect(result.crawler).toBe('preflight');
+ expect(result.data).toMatchObject({ errorType: 'InvalidUrlError', retryable: false });
+ expect((result.data as any).content).toContain('Invalid URL');
+ expect(crawlImpls.naive).not.toHaveBeenCalled();
+ expect(crawlImpls.jina).not.toHaveBeenCalled();
+ });
+
+ it('should repair a bare domain by prepending https:// and report the transformed url', async () => {
+ const mockResult = {
+ content: 'test content'.padEnd(101, ' '),
+ contentType: 'text' as const,
+ url: 'https://example.com/docs',
+ };
+
+ const { crawlImpls } = await import('../crawImpl');
+ vi.mocked(crawlImpls.naive).mockResolvedValue(mockResult);
+
+ const { applyUrlRules } = await import('../utils/appUrlRules');
+ vi.mocked(applyUrlRules).mockImplementation((url) => ({ transformedUrl: url }));
+
+ const result = await crawler.crawl({ url: 'example.com/docs' });
+
+ expect(applyUrlRules).toHaveBeenCalledWith('https://example.com/docs', expect.anything());
+ expect(crawlImpls.naive).toHaveBeenCalledWith('https://example.com/docs', expect.anything());
+ expect(result).toEqual({
+ crawler: 'naive',
+ data: mockResult,
+ originalUrl: 'example.com/docs',
+ transformedUrl: 'https://example.com/docs',
+ });
+ });
+
+ it('should reject resource files (images / fonts / media) without calling any impl', async () => {
+ const { crawlImpls } = await import('../crawImpl');
+
+ for (const url of [
+ 'https://lobe.example.com:8443/app-icons/icon-512x512.png',
+ 'https://example.no/assets/logo.svg?v=3',
+ 'https://cdn.example.com/fonts/inter.woff2',
+ 'https://example.com/clip.mp4',
+ ]) {
+ const result = await crawler.crawl({ url });
+
+ expect(result.crawler).toBe('preflight');
+ expect(result.data).toMatchObject({
+ errorType: 'UnsupportedContentError',
+ retryable: false,
+ });
+ }
+
+ expect(crawlImpls.naive).not.toHaveBeenCalled();
+ expect(crawlImpls.jina).not.toHaveBeenCalled();
+ expect(crawlImpls.search1api).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('dead links', () => {
+ it('should stop trying other impls once a page is confirmed 404 and mark it non-retryable', async () => {
+ const { crawlImpls } = await import('../crawImpl');
+ vi.mocked(crawlImpls.jina).mockRejectedValue(new Error('jina failed'));
+ vi.mocked(crawlImpls.naive).mockRejectedValue(new PageNotFoundError('Not Found', 404));
+
+ const result = await crawler.crawl({ url: 'https://example.com/missing' });
+
+ expect(crawlImpls.jina).toHaveBeenCalledTimes(1);
+ expect(crawlImpls.naive).toHaveBeenCalledTimes(1);
+ expect(crawlImpls.search1api).not.toHaveBeenCalled();
+ expect(crawlImpls.browserless).not.toHaveBeenCalled();
+ expect(result.crawler).toBe('naive');
+ expect(result.data).toMatchObject({
+ errorType: 'PageNotFoundError',
+ errorMessage: 'Not Found',
+ retryable: false,
+ });
+ expect((result.data as any).content).toContain('HTTP 404');
+ expect((result.data as any).content).toContain('do not retry');
+ });
+
+ it('should treat 410 Gone the same way', async () => {
+ const { crawlImpls } = await import('../crawImpl');
+ vi.mocked(crawlImpls.jina).mockRejectedValue(new PageNotFoundError('Gone', 410));
+
+ const result = await crawler.crawl({ url: 'https://example.com/removed' });
+
+ expect(crawlImpls.naive).not.toHaveBeenCalled();
+ expect((result.data as any).content).toContain('HTTP 410');
+ expect(result.data).toMatchObject({ retryable: false });
+ });
+ });
+
+ describe('retryable flag', () => {
+ it('should leave transient failures retryable', async () => {
+ const { crawlImpls } = await import('../crawImpl');
+ const transient = new HTTPStatusError('Provider request failed with status 502', 502);
+ vi.mocked(crawlImpls.naive).mockRejectedValue(transient);
+ vi.mocked(crawlImpls.jina).mockRejectedValue(transient);
+ vi.mocked(crawlImpls.search1api).mockRejectedValue(transient);
+ vi.mocked(crawlImpls.browserless).mockRejectedValue(transient);
+
+ const result = await crawler.crawl({ url: 'https://example.com' });
+
+ expect(result.data).not.toHaveProperty('retryable');
+ expect(result.data).toMatchObject({ errorType: 'HTTPStatusError' });
+ });
+
+ it('should mark a provider 4xx rejection (e.g. non-document content) non-retryable', async () => {
+ const { crawlImpls } = await import('../crawImpl');
+ const rejected = new HTTPStatusError(
+ 'Search1API request failed with status 400: Bad Request. Response: URL points to non-document content (image/svg+xml)',
+ 400,
+ );
+ vi.mocked(crawlImpls.naive).mockRejectedValue(rejected);
+ vi.mocked(crawlImpls.jina).mockRejectedValue(rejected);
+ vi.mocked(crawlImpls.search1api).mockRejectedValue(rejected);
+ vi.mocked(crawlImpls.browserless).mockRejectedValue(rejected);
+
+ const result = await crawler.crawl({ url: 'https://example.com' });
+
+ expect(result.data).toMatchObject({ errorType: 'HTTPStatusError', retryable: false });
+ });
+ });
});
diff --git a/packages/web-crawler/src/crawImpl/__tests__/naive.test.ts b/packages/web-crawler/src/crawImpl/__tests__/naive.test.ts
index 464a5653de5..0bb9bca2451 100644
--- a/packages/web-crawler/src/crawImpl/__tests__/naive.test.ts
+++ b/packages/web-crawler/src/crawImpl/__tests__/naive.test.ts
@@ -1,6 +1,11 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { NetworkConnectionError, PageNotFoundError, TimeoutError } from '../../utils/errorType';
+import {
+ NetworkConnectionError,
+ PageNotFoundError,
+ TimeoutError,
+ UnsupportedContentError,
+} from '../../utils/errorType';
import { naive } from '../naive';
// Mock dependencies
@@ -55,6 +60,41 @@ describe('naive crawler', () => {
});
});
+ it('should throw UnsupportedContentError for non-document content types', async () => {
+ const { withTimeout } = await import('../../utils/withTimeout');
+ const { htmlToMarkdown } = await import('../../utils/htmlToMarkdown');
+
+ for (const contentType of ['image/png', 'image/svg+xml', 'font/woff2', 'video/mp4']) {
+ vi.mocked(withTimeout).mockResolvedValue({
+ status: 200,
+ ok: true,
+ headers: new Map([['content-type', contentType]]),
+ text: vi.fn().mockResolvedValue('binary'),
+ } as any);
+
+ await expect(naive('https://example.com/asset', { filterOptions: {} })).rejects.toThrow(
+ UnsupportedContentError,
+ );
+ }
+
+ expect(htmlToMarkdown).not.toHaveBeenCalled();
+ });
+
+ it('should throw PageNotFoundError with status for 410 Gone', async () => {
+ const { withTimeout } = await import('../../utils/withTimeout');
+ vi.mocked(withTimeout).mockResolvedValue({
+ status: 410,
+ ok: false,
+ statusText: 'Gone',
+ headers: new Map(),
+ text: vi.fn().mockResolvedValue(''),
+ } as any);
+
+ await expect(naive('https://example.com/removed', { filterOptions: {} })).rejects.toMatchObject(
+ { name: 'PageNotFoundError', status: 410 },
+ );
+ });
+
it('should successfully crawl JSON content', async () => {
const mockJsonData = { message: 'Hello world', data: [1, 2, 3] };
const mockResponse = {
diff --git a/packages/web-crawler/src/crawImpl/__tests__/search1api.test.ts b/packages/web-crawler/src/crawImpl/__tests__/search1api.test.ts
index 2e2981f71cb..2a91de83732 100644
--- a/packages/web-crawler/src/crawImpl/__tests__/search1api.test.ts
+++ b/packages/web-crawler/src/crawImpl/__tests__/search1api.test.ts
@@ -1,7 +1,13 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createMockResponse } from '../../test-utils';
-import { NetworkConnectionError, PageNotFoundError, TimeoutError } from '../../utils/errorType';
+import {
+ HTTPStatusError,
+ isRetryableCrawlError,
+ NetworkConnectionError,
+ PageNotFoundError,
+ TimeoutError,
+} from '../../utils/errorType';
import * as withTimeoutModule from '../../utils/withTimeout';
import { search1api } from '../search1api';
@@ -64,6 +70,36 @@ describe('search1api crawler', () => {
);
});
+ it('should throw PageNotFoundError carrying the status when the target is 410 Gone', async () => {
+ mockFetch.mockResolvedValue(
+ createMockResponse('Gone', { ok: false, status: 410, statusText: 'Gone' }),
+ );
+
+ await expect(search1api('https://example.com', { filterOptions: {} })).rejects.toMatchObject({
+ name: 'PageNotFoundError',
+ status: 410,
+ });
+ });
+
+ it('should throw a non-retryable HTTPStatusError with the provider message on 400', async () => {
+ mockFetch.mockResolvedValue(
+ createMockResponse('URL points to non-document content (image/svg+xml)', {
+ ok: false,
+ status: 400,
+ statusText: 'Bad Request',
+ }),
+ );
+
+ const error = await search1api('https://example.com/logo.svg', { filterOptions: {} }).catch(
+ (e) => e,
+ );
+
+ expect(error).toBeInstanceOf(HTTPStatusError);
+ expect(error.status).toBe(400);
+ expect(error.message).toContain('URL points to non-document content (image/svg+xml)');
+ expect(isRetryableCrawlError(error)).toBe(false);
+ });
+
it('should throw error for other failed responses', async () => {
mockFetch.mockResolvedValue(
createMockResponse('', {
diff --git a/packages/web-crawler/src/crawImpl/naive.ts b/packages/web-crawler/src/crawImpl/naive.ts
index 57cf7be87cd..1c3a67bebaf 100755
--- a/packages/web-crawler/src/crawImpl/naive.ts
+++ b/packages/web-crawler/src/crawImpl/naive.ts
@@ -1,9 +1,10 @@
import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';
import type { CrawlImpl, CrawlSuccessResult } from '../type';
-import { PageNotFoundError, toFetchError } from '../utils/errorType';
+import { PageNotFoundError, toFetchError, UnsupportedContentError } from '../utils/errorType';
import { htmlToMarkdown, MAX_HTML_SIZE } from '../utils/htmlToMarkdown';
import { createHTTPStatusError } from '../utils/response';
+import { isNonDocumentContentType } from '../utils/urlPreflight';
import { DEFAULT_TIMEOUT, withTimeout } from '../utils/withTimeout';
const mixinHeaders = {
@@ -55,8 +56,8 @@ export const naive: CrawlImpl = async (url, { filterOptions }) => {
throw toFetchError(e);
}
- if (res.status === 404) {
- throw new PageNotFoundError(res.statusText);
+ if (res.status === 404 || res.status === 410) {
+ throw new PageNotFoundError(res.statusText, res.status);
}
if (!res.ok) {
@@ -65,6 +66,12 @@ export const naive: CrawlImpl = async (url, { filterOptions }) => {
const type = res.headers.get('content-type');
+ // images / fonts / media / archives have no readable body β€” surface that instead of
+ // handing binary bytes to the HTML parser (and falling through to the next provider)
+ if (isNonDocumentContentType(type)) {
+ throw new UnsupportedContentError(`URL points to non-document content (${type})`);
+ }
+
if (type?.includes('application/json')) {
let content: string;
diff --git a/packages/web-crawler/src/crawImpl/search1api.ts b/packages/web-crawler/src/crawImpl/search1api.ts
index edc6f690f17..2c90fd4c9c1 100644
--- a/packages/web-crawler/src/crawImpl/search1api.ts
+++ b/packages/web-crawler/src/crawImpl/search1api.ts
@@ -41,8 +41,8 @@ export const search1api: CrawlImpl = async (url) => {
}
if (!res.ok) {
- if (res.status === 404) {
- throw new PageNotFoundError(res.statusText);
+ if (res.status === 404 || res.status === 410) {
+ throw new PageNotFoundError(res.statusText, res.status);
}
throw await createHTTPStatusError(res, 'Search1API');
diff --git a/packages/web-crawler/src/crawler.ts b/packages/web-crawler/src/crawler.ts
index dcad7d3b3bb..a05ab5cbfb5 100644
--- a/packages/web-crawler/src/crawler.ts
+++ b/packages/web-crawler/src/crawler.ts
@@ -1,15 +1,55 @@
import type { CrawlImplType } from './crawImpl';
import { crawlImpls } from './crawImpl';
-import type { CrawlUniformResult, CrawlUrlRule } from './type';
+import type { CrawlErrorResult, CrawlUniformResult, CrawlUrlRule } from './type';
import { crawUrlRules } from './urlRules';
import { applyUrlRules } from './utils/appUrlRules';
+import {
+ InvalidUrlError,
+ isRetryableCrawlError,
+ PageNotFoundError,
+ UnsupportedContentError,
+} from './utils/errorType';
+import { getNonDocumentExtension, normalizeCrawlUrl } from './utils/urlPreflight';
const defaultImpls = ['jina', 'naive', 'search1api', 'browserless'] as CrawlImplType[];
+/** Pseudo crawler name for failures raised before any provider was contacted. */
+const PREFLIGHT_CRAWLER = 'preflight';
+
interface CrawlOptions {
impls?: string[];
}
+/**
+ * Build the error payload handed back to the model. Authoritative failures get an
+ * explicit "this is final, do not retry" message so the model changes strategy
+ * instead of re-issuing the same (billed) request.
+ */
+const buildErrorData = (error: Error | undefined): CrawlErrorResult => {
+ const errorType = error?.name || 'UnknownError';
+ const errorMessage = error?.message;
+ const retryable = isRetryableCrawlError(error);
+
+ let content: string;
+
+ if (error instanceof PageNotFoundError) {
+ content = `Dead link: the server confirmed this page does not exist (HTTP ${error.status}). This is a final answer β€” do not retry this URL; find a different source instead.`;
+ } else if (error instanceof InvalidUrlError) {
+ content = `Invalid URL: ${errorMessage}. Nothing was fetched β€” pass an absolute http(s) URL.`;
+ } else if (error instanceof UnsupportedContentError) {
+ content = `Unsupported content: ${errorMessage}. Nothing to read here β€” only crawl HTML/text document pages.`;
+ } else {
+ content = `Fail to crawl the page. Error type: ${errorType}, error message: ${errorMessage}`;
+ }
+
+ return {
+ content,
+ errorMessage,
+ errorType,
+ ...(retryable ? {} : { retryable: false }),
+ };
+};
+
export class Crawler {
impls: CrawlImplType[];
@@ -32,12 +72,33 @@ export class Crawler {
impls?: CrawlImplType[];
url: string;
}): Promise<CrawlUniformResult> {
+ // Preflight: repair or reject the URL before any provider (and its quota) is touched.
+ let normalizedUrl = url;
+
+ try {
+ normalizedUrl = normalizeCrawlUrl(url);
+
+ const resourceExtension = getNonDocumentExtension(normalizedUrl);
+ if (resourceExtension) {
+ throw new UnsupportedContentError(
+ `URL points to a .${resourceExtension} resource file, which has no readable page content`,
+ );
+ }
+ } catch (error) {
+ return {
+ crawler: PREFLIGHT_CRAWLER,
+ data: buildErrorData(error as Error),
+ originalUrl: url,
+ transformedUrl: normalizedUrl !== url ? normalizedUrl : undefined,
+ };
+ }
+
// Apply URL rules
const {
transformedUrl,
filterOptions: ruleFilterOptions,
impls: ruleImpls,
- } = applyUrlRules(url, crawUrlRules);
+ } = applyUrlRules(normalizedUrl, crawUrlRules);
// Merge user-provided filter options and rule filter options, user options take priority
const mergedFilterOptions = {
@@ -83,19 +144,16 @@ export class Crawler {
console.error(`[${impl}]`, error);
finalError = error as Error;
finalCrawler = impl;
+
+ // A confirmed 404/410 is the page's final answer; asking the next provider
+ // only buys the same "not found" again.
+ if (error instanceof PageNotFoundError) break;
}
}
- const errorType = finalError?.name || 'UnknownError';
- const errorMessage = finalError?.message;
-
return {
crawler: finalCrawler || finalImpls.at(-1) || 'unknown',
- data: {
- content: `Fail to crawl the page. Error type: ${errorType}, error message: ${errorMessage}`,
- errorMessage,
- errorType,
- },
+ data: buildErrorData(finalError),
originalUrl: url,
transformedUrl: transformedUrl !== url ? transformedUrl : undefined,
};
diff --git a/packages/web-crawler/src/index.ts b/packages/web-crawler/src/index.ts
index 70edcebd9ba..9f3c3bf9241 100644
--- a/packages/web-crawler/src/index.ts
+++ b/packages/web-crawler/src/index.ts
@@ -1,3 +1,17 @@
export type { CrawlImplType } from './crawImpl';
export { Crawler } from './crawler';
export * from './type';
+export {
+ HTTPStatusError,
+ InvalidUrlError,
+ isRetryableCrawlError,
+ NetworkConnectionError,
+ PageNotFoundError,
+ TimeoutError,
+ UnsupportedContentError,
+} from './utils/errorType';
+export {
+ getNonDocumentExtension,
+ isNonDocumentContentType,
+ normalizeCrawlUrl,
+} from './utils/urlPreflight';
diff --git a/packages/web-crawler/src/type.ts b/packages/web-crawler/src/type.ts
index 5c996d42d83..d38805c3305 100644
--- a/packages/web-crawler/src/type.ts
+++ b/packages/web-crawler/src/type.ts
@@ -12,6 +12,11 @@ export interface CrawlErrorResult {
content: string;
errorMessage?: string;
errorType?: string;
+ /**
+ * `false` when re-issuing the same crawl cannot succeed (dead link, invalid URL,
+ * resource file, rejected request). Absent means a retry may be worthwhile.
+ */
+ retryable?: boolean;
url?: string;
}
diff --git a/packages/web-crawler/src/utils/__tests__/errorType.test.ts b/packages/web-crawler/src/utils/__tests__/errorType.test.ts
index d2ad87c793a..a8aeb91e489 100644
--- a/packages/web-crawler/src/utils/__tests__/errorType.test.ts
+++ b/packages/web-crawler/src/utils/__tests__/errorType.test.ts
@@ -1,11 +1,15 @@
import { describe, expect, it } from 'vitest';
import {
+ HTTPStatusError,
+ InvalidUrlError,
isFetchNetworkError,
+ isRetryableCrawlError,
NetworkConnectionError,
PageNotFoundError,
TimeoutError,
toFetchError,
+ UnsupportedContentError,
} from '../errorType';
describe('errorType', () => {
@@ -235,7 +239,7 @@ describe('errorType', () => {
expect(e.name).toBe('TimeoutError');
expect(e.message).toBe('timeout error');
} else {
- throw new Error('Unexpected error type');
+ throw new Error('Unexpected error type', { cause: e });
}
}
});
@@ -258,3 +262,28 @@ describe('errorType', () => {
});
});
});
+
+describe('isRetryableCrawlError', () => {
+ it('should never retry authoritative failures', () => {
+ expect(isRetryableCrawlError(new PageNotFoundError('Not Found'))).toBe(false);
+ expect(isRetryableCrawlError(new PageNotFoundError('Gone', 410))).toBe(false);
+ expect(isRetryableCrawlError(new InvalidUrlError('bad'))).toBe(false);
+ expect(isRetryableCrawlError(new UnsupportedContentError('svg'))).toBe(false);
+ });
+
+ it('should not retry provider 4xx rejections except 408/429', () => {
+ expect(isRetryableCrawlError(new HTTPStatusError('400', 400))).toBe(false);
+ expect(isRetryableCrawlError(new HTTPStatusError('401', 401))).toBe(false);
+ expect(isRetryableCrawlError(new HTTPStatusError('422', 422))).toBe(false);
+ expect(isRetryableCrawlError(new HTTPStatusError('408', 408))).toBe(true);
+ expect(isRetryableCrawlError(new HTTPStatusError('429', 429))).toBe(true);
+ });
+
+ it('should retry transient failures', () => {
+ expect(isRetryableCrawlError(new HTTPStatusError('502', 502))).toBe(true);
+ expect(isRetryableCrawlError(new NetworkConnectionError())).toBe(true);
+ expect(isRetryableCrawlError(new TimeoutError('timeout'))).toBe(true);
+ expect(isRetryableCrawlError(new Error('unknown'))).toBe(true);
+ expect(isRetryableCrawlError(undefined)).toBe(true);
+ });
+});
diff --git a/packages/web-crawler/src/utils/__tests__/urlPreflight.test.ts b/packages/web-crawler/src/utils/__tests__/urlPreflight.test.ts
new file mode 100644
index 00000000000..68ea72ecb29
--- /dev/null
+++ b/packages/web-crawler/src/utils/__tests__/urlPreflight.test.ts
@@ -0,0 +1,119 @@
+import { describe, expect, it } from 'vitest';
+
+import { InvalidUrlError } from '../errorType';
+import {
+ getNonDocumentExtension,
+ isNonDocumentContentType,
+ normalizeCrawlUrl,
+} from '../urlPreflight';
+
+describe('normalizeCrawlUrl', () => {
+ it('should return a valid absolute url untouched', () => {
+ expect(normalizeCrawlUrl('https://example.com/a?b=1#c')).toBe('https://example.com/a?b=1#c');
+ expect(normalizeCrawlUrl('http://localhost:3000/path')).toBe('http://localhost:3000/path');
+ });
+
+ it('should prepend https:// to a bare domain / path', () => {
+ expect(normalizeCrawlUrl('example.com')).toBe('https://example.com');
+ expect(normalizeCrawlUrl('www.example.com/docs/intro')).toBe(
+ 'https://www.example.com/docs/intro',
+ );
+ expect(normalizeCrawlUrl('lobe.zhouyu.li:8443/app')).toBe('https://lobe.zhouyu.li:8443/app');
+ expect(normalizeCrawlUrl('//cdn.example.com/x')).toBe('https://cdn.example.com/x');
+ });
+
+ it('should unwrap markdown links, angle brackets, quotes and trailing punctuation', () => {
+ expect(normalizeCrawlUrl('[LobeHub](https://lobehub.com/docs)')).toBe(
+ 'https://lobehub.com/docs',
+ );
+ expect(normalizeCrawlUrl('[LobeHub](https://lobehub.com/docs "title")')).toBe(
+ 'https://lobehub.com/docs',
+ );
+ expect(normalizeCrawlUrl('<https://example.com/a>')).toBe('https://example.com/a');
+ expect(normalizeCrawlUrl('"https://example.com/a"')).toBe('https://example.com/a');
+ expect(normalizeCrawlUrl(' https://example.com/a. ')).toBe('https://example.com/a');
+ expect(normalizeCrawlUrl('https://example.com/a),')).toBe('https://example.com/a');
+ expect(normalizeCrawlUrl('[docs](example.com/docs)')).toBe('https://example.com/docs');
+ });
+
+ it('should keep balanced parentheses that are part of the url', () => {
+ expect(normalizeCrawlUrl('https://en.wikipedia.org/wiki/Foo_(bar)')).toBe(
+ 'https://en.wikipedia.org/wiki/Foo_(bar)',
+ );
+ });
+
+ it('should throw InvalidUrlError for text that is not a url', () => {
+ for (const input of [
+ '',
+ ' ',
+ 'not a url at all',
+ 'search for lobehub pricing',
+ 'ftp://example.com/file',
+ 'mailto:[email protected]',
+ 'javascript:alert(1)',
+ ]) {
+ expect(() => normalizeCrawlUrl(input)).toThrow(InvalidUrlError);
+ }
+ });
+
+ it('should handle long runs of wrapping characters without backtracking', () => {
+ // these shapes made the previous anchored `[…]+$` regexes backtrack quadratically
+ expect(normalizeCrawlUrl(`https://example.com/a${'"'.repeat(50_000)}`)).toBe(
+ 'https://example.com/a',
+ );
+ expect(normalizeCrawlUrl(`https://example.com/a${'\t'.repeat(50_000)}`)).toBe(
+ 'https://example.com/a',
+ );
+ expect(normalizeCrawlUrl(`https://example.com/a${')'.repeat(50_000)}`)).toBe(
+ 'https://example.com/a',
+ );
+ expect(() => normalizeCrawlUrl('"'.repeat(50_000))).toThrow(InvalidUrlError);
+ });
+
+ it('should truncate very long inputs in the error message', () => {
+ const long = 'x'.repeat(500);
+ expect(() => normalizeCrawlUrl(long)).toThrow(/…/);
+ });
+});
+
+describe('getNonDocumentExtension', () => {
+ it('should detect images, fonts, media and archives by extension', () => {
+ expect(getNonDocumentExtension('https://a.com/app-icons/icon-512x512.png')).toBe('png');
+ expect(getNonDocumentExtension('https://a.com/logo.SVG?v=1')).toBe('svg');
+ expect(getNonDocumentExtension('https://a.com/fonts/inter.woff2')).toBe('woff2');
+ expect(getNonDocumentExtension('https://a.com/shot-1.mobile.png')).toBe('png');
+ expect(getNonDocumentExtension('https://a.com/video.mp4#t=10')).toBe('mp4');
+ expect(getNonDocumentExtension('https://a.com/release.zip')).toBe('zip');
+ });
+
+ it('should allow document-like urls', () => {
+ expect(getNonDocumentExtension('https://a.com/')).toBeUndefined();
+ expect(getNonDocumentExtension('https://a.com/docs/intro')).toBeUndefined();
+ expect(getNonDocumentExtension('https://a.com/page.html')).toBeUndefined();
+ expect(getNonDocumentExtension('https://a.com/paper.pdf')).toBeUndefined();
+ expect(getNonDocumentExtension('https://a.com/data.json')).toBeUndefined();
+ expect(getNonDocumentExtension('https://a.com/v2.0.1')).toBeUndefined();
+ expect(getNonDocumentExtension('https://a.com/.env')).toBeUndefined();
+ expect(getNonDocumentExtension('not a url')).toBeUndefined();
+ });
+});
+
+describe('isNonDocumentContentType', () => {
+ it('should flag binary media types', () => {
+ expect(isNonDocumentContentType('image/png')).toBe(true);
+ expect(isNonDocumentContentType('image/svg+xml; charset=utf-8')).toBe(true);
+ expect(isNonDocumentContentType('font/woff2')).toBe(true);
+ expect(isNonDocumentContentType('video/mp4')).toBe(true);
+ expect(isNonDocumentContentType('application/octet-stream')).toBe(true);
+ expect(isNonDocumentContentType('APPLICATION/ZIP')).toBe(true);
+ });
+
+ it('should allow textual types', () => {
+ expect(isNonDocumentContentType('text/html; charset=utf-8')).toBe(false);
+ expect(isNonDocumentContentType('application/json')).toBe(false);
+ expect(isNonDocumentContentType('application/pdf')).toBe(false);
+ expect(isNonDocumentContentType('text/plain')).toBe(false);
+ expect(isNonDocumentContentType(undefined)).toBe(false);
+ expect(isNonDocumentContentType(null)).toBe(false);
+ });
+});
diff --git a/packages/web-crawler/src/utils/errorType.ts b/packages/web-crawler/src/utils/errorType.ts
index fc4e4fbb3df..aa94b4af571 100644
--- a/packages/web-crawler/src/utils/errorType.ts
+++ b/packages/web-crawler/src/utils/errorType.ts
@@ -1,9 +1,55 @@
+/**
+ * The target server authoritatively confirmed the page does not exist (HTTP 404/410).
+ * This is a final answer, not a transient failure β€” retrying it (or asking another
+ * provider) only re-buys the same "nothing here" and, for metered providers, is billed.
+ */
export class PageNotFoundError extends Error {
- constructor(message: string) {
+ status: number;
+
+ constructor(message: string, status: number = 404) {
super(message);
this.name = 'PageNotFoundError';
+ this.status = status;
+ }
+}
+
+/**
+ * The input could not be turned into an absolute http(s) URL even after normalization
+ * (bare text, unsupported scheme, ...). Nothing was sent to any provider.
+ */
+export class InvalidUrlError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'InvalidUrlError';
+ }
+}
+
+/**
+ * The URL points at a resource file (image / font / video / archive ...) that has no
+ * readable body. Nothing was sent to any provider.
+ */
+export class UnsupportedContentError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'UnsupportedContentError';
}
}
+
+/**
+ * A crawl provider answered with a non-2xx status that is not a dead link.
+ * `status` lets callers decide whether the failure is transient (5xx / 429 / 408)
+ * or a rejected request (other 4xx) that will fail the same way on retry.
+ */
+export class HTTPStatusError extends Error {
+ status: number;
+
+ constructor(message: string, status: number) {
+ super(message);
+ this.name = 'HTTPStatusError';
+ this.status = status;
+ }
+}
+
export class NetworkConnectionError extends Error {
constructor() {
super('Network connection error');
@@ -18,6 +64,31 @@ export class TimeoutError extends Error {
}
}
+const RETRYABLE_HTTP_STATUS = new Set([408, 429]);
+
+/**
+ * Whether re-issuing the exact same crawl could plausibly succeed.
+ *
+ * - dead link (404/410), invalid URL, resource file: authoritative β†’ never retry
+ * - provider 4xx other than 408/429: request was rejected β†’ never retry
+ * - network / timeout / 5xx / 429 / 408 / empty body: transient β†’ retry is fine
+ */
+export const isRetryableCrawlError = (error: unknown): boolean => {
+ if (
+ error instanceof PageNotFoundError ||
+ error instanceof InvalidUrlError ||
+ error instanceof UnsupportedContentError
+ ) {
+ return false;
+ }
+
+ if (error instanceof HTTPStatusError) {
+ return error.status >= 500 || RETRYABLE_HTTP_STATUS.has(error.status);
+ }
+
+ return true;
+};
+
/**
* Check if an error is a Node.js fetch network failure.
* Node.js undici throws TypeError with message "fetch failed" on network errors.
diff --git a/packages/web-crawler/src/utils/response.ts b/packages/web-crawler/src/utils/response.ts
index 901ffffdcb1..c724e7f9fbd 100644
--- a/packages/web-crawler/src/utils/response.ts
+++ b/packages/web-crawler/src/utils/response.ts
@@ -1,3 +1,5 @@
+import { HTTPStatusError } from './errorType';
+
const ERROR_BODY_SNIPPET_LIMIT = 200;
const normalizeBodySnippet = (body: string) => body.replaceAll(/\s+/g, ' ').trim();
@@ -38,12 +40,13 @@ export const parseJSONResponse = async <T>(response: Response, provider: string)
export const createHTTPStatusError = async (
response: Response,
provider: string,
-): Promise<Error> => {
+): Promise<HTTPStatusError> => {
const bodySnippet = await getBodySnippet(response);
- return new Error(
+ return new HTTPStatusError(
bodySnippet
? `${provider} request failed with status ${response.status}: ${response.statusText}. Response: ${bodySnippet}`
: `${provider} request failed with status ${response.status}: ${response.statusText}`,
+ response.status,
);
};
diff --git a/packages/web-crawler/src/utils/urlPreflight.ts b/packages/web-crawler/src/utils/urlPreflight.ts
new file mode 100644
index 00000000000..d04121c20e4
--- /dev/null
+++ b/packages/web-crawler/src/utils/urlPreflight.ts
@@ -0,0 +1,252 @@
+import { InvalidUrlError } from './errorType';
+
+/**
+ * File extensions that never carry a readable page body. Crawling them wastes a
+ * (billed) provider call and always ends in an empty result, so they are rejected
+ * before any provider is contacted.
+ */
+const NON_DOCUMENT_EXTENSIONS = new Set([
+ // images
+ 'apng',
+ 'avif',
+ 'bmp',
+ 'gif',
+ 'heic',
+ 'ico',
+ 'jpeg',
+ 'jpg',
+ 'png',
+ 'svg',
+ 'tif',
+ 'tiff',
+ 'webp',
+ // fonts
+ 'eot',
+ 'otf',
+ 'ttf',
+ 'woff',
+ 'woff2',
+ // audio / video
+ 'aac',
+ 'avi',
+ 'flac',
+ 'flv',
+ 'm4a',
+ 'm4v',
+ 'mkv',
+ 'mov',
+ 'mp3',
+ 'mp4',
+ 'ogg',
+ 'wav',
+ 'webm',
+ // archives / binaries
+ '7z',
+ 'apk',
+ 'bin',
+ 'bz2',
+ 'deb',
+ 'dmg',
+ 'exe',
+ 'gz',
+ 'iso',
+ 'msi',
+ 'rar',
+ 'rpm',
+ 'tar',
+ 'tgz',
+ 'wasm',
+ 'xz',
+ 'zip',
+]);
+
+const NON_DOCUMENT_CONTENT_TYPE_PREFIXES = ['audio/', 'font/', 'image/', 'video/'];
+
+const NON_DOCUMENT_CONTENT_TYPES = new Set([
+ 'application/font-sfnt',
+ 'application/font-woff',
+ 'application/font-woff2',
+ 'application/gzip',
+ 'application/octet-stream',
+ 'application/vnd.ms-fontobject',
+ 'application/wasm',
+ 'application/x-7z-compressed',
+ 'application/x-font-ttf',
+ 'application/x-rar-compressed',
+ 'application/x-tar',
+ 'application/zip',
+]);
+
+const SCHEME_RE = /^[a-z][\d+.a-z-]*:/i;
+const HTTP_SCHEME_RE = /^https?:\/\//i;
+// "example.com:8443/app" β€” a port, not a scheme
+const HOST_PORT_RE = /^[^/:]+:\d+(?:\/|$)/;
+const MARKDOWN_LINK_RE = /^\[[^\]]*\]\(\s*<?([^\s)>]+)>?(?:\s+["'][^"']*["'])?\s*\)$/;
+
+const LEADING_WRAPPERS = new Set(['<', '"', "'", '`']);
+const TRAILING_WRAPPERS = new Set(['>', '"', "'", '`']);
+// sentence punctuation the model tends to glue onto a link
+const TRAILING_PUNCTUATION = new Set([
+ ' ',
+ '\t',
+ '\n',
+ '\r',
+ '!',
+ ',',
+ '.',
+ ':',
+ ';',
+ '?',
+ "'",
+ '"',
+ '`',
+]);
+
+// Character-set trimming is done with loops rather than anchored `[…]+$` regexes:
+// this input is model- and user-controlled, and those regexes backtrack
+// quadratically on long runs of the trimmed characters.
+const trimStart = (value: string, chars: Set<string>): string => {
+ let start = 0;
+ while (start < value.length && chars.has(value[start])) start++;
+
+ return start === 0 ? value : value.slice(start);
+};
+
+const trimEnd = (value: string, chars: Set<string>): string => {
+ let end = value.length;
+ while (end > 0 && chars.has(value[end - 1])) end--;
+
+ return end === value.length ? value : value.slice(0, end);
+};
+
+/**
+ * Drop trailing ")" that closes a parenthesis opened outside the URL, as in
+ * prose like "(see https://example.com)". Parens balanced within the URL stay.
+ */
+const trimUnbalancedTrailingParens = (value: string): string => {
+ let opened = 0;
+ let closed = 0;
+
+ for (const char of value) {
+ if (char === '(') opened++;
+ else if (char === ')') closed++;
+ }
+
+ let end = value.length;
+ let unbalanced = closed - opened;
+ while (unbalanced > 0 && end > 0 && value[end - 1] === ')') {
+ end--;
+ unbalanced--;
+ }
+
+ return end === value.length ? value : value.slice(0, end);
+};
+
+/**
+ * Return the resource-file extension of a URL path (lower-cased, without the dot),
+ * or `undefined` when the path does not end in a known non-document extension.
+ */
+export const getNonDocumentExtension = (url: string): string | undefined => {
+ let pathname: string;
+
+ try {
+ pathname = new URL(url).pathname;
+ } catch {
+ return undefined;
+ }
+
+ const lastSegment = pathname.split('/').pop() ?? '';
+ const dotIndex = lastSegment.lastIndexOf('.');
+
+ if (dotIndex <= 0) return undefined;
+
+ const ext = lastSegment.slice(dotIndex + 1).toLowerCase();
+
+ return NON_DOCUMENT_EXTENSIONS.has(ext) ? ext : undefined;
+};
+
+/**
+ * Whether a response `Content-Type` describes bytes that have no readable page body.
+ */
+export const isNonDocumentContentType = (contentType?: string | null): boolean => {
+ if (!contentType) return false;
+
+ const mime = contentType.split(';')[0].trim().toLowerCase();
+
+ return (
+ NON_DOCUMENT_CONTENT_TYPES.has(mime) ||
+ NON_DOCUMENT_CONTENT_TYPE_PREFIXES.some((prefix) => mime.startsWith(prefix))
+ );
+};
+
+const stripWrapping = (input: string): string => {
+ let value = input.trim();
+
+ // markdown link: [label](https://example.com "title")
+ const markdown = value.match(MARKDOWN_LINK_RE);
+ if (markdown) value = markdown[1];
+
+ // <https://example.com>, "https://example.com", `https://example.com`
+ value = trimEnd(trimStart(value, LEADING_WRAPPERS), TRAILING_WRAPPERS);
+
+ value = trimEnd(value, TRAILING_PUNCTUATION);
+
+ return trimUnbalancedTrailingParens(value);
+};
+
+const isPlausibleHostname = (hostname: string): boolean =>
+ hostname === 'localhost' || hostname.includes('.') || hostname.includes(':');
+
+const parseHttpUrl = (candidate: string): URL | undefined => {
+ let parsed: URL;
+
+ try {
+ parsed = new URL(candidate);
+ } catch {
+ return undefined;
+ }
+
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return undefined;
+ if (!isPlausibleHostname(parsed.hostname)) return undefined;
+
+ return parsed;
+};
+
+/**
+ * Turn a model-generated string into an absolute http(s) URL, or throw `InvalidUrlError`.
+ *
+ * Repairs the shapes that dominate provider-side 422s β€” bare domains without a scheme,
+ * markdown links, surrounding quotes / angle brackets, trailing punctuation β€” and rejects
+ * everything that still does not parse as http(s) so no provider call is made for it.
+ *
+ * Returns the input untouched (modulo trimming) when it is already a clean absolute
+ * http(s) URL.
+ */
+export const normalizeCrawlUrl = (input: string): string => {
+ if (typeof input !== 'string' || input.trim().length === 0) {
+ throw new InvalidUrlError('URL is empty');
+ }
+
+ const stripped = stripWrapping(input);
+ const candidates = [stripped];
+
+ if (stripped.startsWith('//')) {
+ candidates.push(`https:${stripped}`);
+ } else if (
+ !HTTP_SCHEME_RE.test(stripped) &&
+ (!SCHEME_RE.test(stripped) || HOST_PORT_RE.test(stripped))
+ ) {
+ // no scheme (or a host:port that only looks like one) β†’ assume https
+ candidates.push(`https://${stripped}`);
+ }
+
+ for (const candidate of candidates) {
+ if (parseHttpUrl(candidate)) return candidate;
+ }
+
+ const preview = input.length > 120 ? `${input.slice(0, 120)}…` : input;
+
+ throw new InvalidUrlError(
+ `"${preview}" is not a valid absolute http(s) URL (expected something like https://example.com/path)`,
+ );
+};
diff --git a/src/store/tool/slices/builtin/executors/__tests__/lobe-web-browsing.test.ts b/src/store/tool/slices/builtin/executors/__tests__/lobe-web-browsing.test.ts
index 3738bb60e4d..bc298d3ba40 100644
--- a/src/store/tool/slices/builtin/executors/__tests__/lobe-web-browsing.test.ts
+++ b/src/store/tool/slices/builtin/executors/__tests__/lobe-web-browsing.test.ts
@@ -274,10 +274,24 @@ describe('WebBrowsingExecutor', () => {
});
it('should handle error items in crawl results', async () => {
+ // crawlPages always nests the per-url outcome under `data` β€” success and
+ // failure alike (see CrawlUniformResult)
const mockResponse = {
results: [
- { data: { title: 'Page 1', content: 'Content 1', url: 'https://example1.com' } },
- { errorMessage: 'Failed to crawl' },
+ {
+ crawler: 'naive',
+ data: { title: 'Page 1', content: 'Content 1', url: 'https://example1.com' },
+ originalUrl: 'https://example1.com',
+ },
+ {
+ crawler: 'naive',
+ data: {
+ content: 'Fail to crawl the page.',
+ errorMessage: 'Failed to crawl',
+ errorType: 'NetworkConnectionError',
+ },
+ originalUrl: 'https://invalid.com',
+ },
],
};
mockCrawlPages.mockResolvedValue(mockResponse);
@@ -289,7 +303,12 @@ describe('WebBrowsingExecutor', () => {
);
expect(result.success).toBe(true);
- expect(result.content).toBeDefined();
+ // the failing url has to survive into the model-facing XML, otherwise the
+ // model cannot tell which of the crawled pages to give up on
+ expect(result.content).toContain('<page url="https://example1.com"');
+ expect(result.content).toContain(
+ '<error errorType="NetworkConnectionError" errorMessage="Failed to crawl" url="https://invalid.com">',
+ );
});
});