@abhishek944/pi-web-access 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ASTACK.md +23 -0
- package/CHANGELOG.md +1289 -0
- package/LICENSE +21 -0
- package/README.md +1215 -2
- package/SECURITY.md +5 -0
- package/abortable.ts +17 -0
- package/activity.ts +101 -0
- package/anysearch.ts +188 -0
- package/auth-fetch.ts +152 -0
- package/baizhi.ts +124 -0
- package/banner.png +0 -0
- package/bocha.ts +203 -0
- package/brave-rate-limit.ts +176 -0
- package/brave.ts +247 -0
- package/brightdata-unlocker.ts +272 -0
- package/ceramic.ts +220 -0
- package/chrome-cookies.ts +752 -0
- package/cloudflare-search.ts +237 -0
- package/content-find.ts +255 -0
- package/crawl4ai.ts +196 -0
- package/credential-source.ts +242 -0
- package/curator-page.ts +3607 -0
- package/curator-run.ts +45 -0
- package/curator-server.ts +761 -0
- package/custom-search.ts +226 -0
- package/data-uri-sanitize.ts +406 -0
- package/datalab-pdf-extract.ts +568 -0
- package/declared-web-links.ts +173 -0
- package/deepseek.ts +377 -0
- package/degoog.ts +323 -0
- package/dist/index.js +28286 -0
- package/dist/mcp-cli.js +29186 -0
- package/dist/pi-mcp.js +20855 -0
- package/dist/types/abortable.d.ts +2 -0
- package/dist/types/activity.d.ts +33 -0
- package/dist/types/anysearch.d.ts +7 -0
- package/dist/types/auth-fetch.d.ts +14 -0
- package/dist/types/baizhi.d.ts +3 -0
- package/dist/types/bocha.d.ts +3 -0
- package/dist/types/brave-rate-limit.d.ts +35 -0
- package/dist/types/brave.d.ts +3 -0
- package/dist/types/brightdata-unlocker.d.ts +11 -0
- package/dist/types/ceramic.d.ts +3 -0
- package/dist/types/chrome-cookies.d.ts +44 -0
- package/dist/types/cloudflare-search.d.ts +4 -0
- package/dist/types/content-find.d.ts +10 -0
- package/dist/types/crawl4ai.d.ts +8 -0
- package/dist/types/credential-source.d.ts +29 -0
- package/dist/types/curator-page.d.ts +5 -0
- package/dist/types/curator-run.d.ts +10 -0
- package/dist/types/curator-server.d.ts +72 -0
- package/dist/types/custom-search.d.ts +22 -0
- package/dist/types/data-uri-sanitize.d.ts +20 -0
- package/dist/types/datalab-pdf-extract.d.ts +59 -0
- package/dist/types/declared-web-links.d.ts +7 -0
- package/dist/types/deepseek.d.ts +13 -0
- package/dist/types/degoog.d.ts +3 -0
- package/dist/types/domain-filter-normalization.d.ts +9 -0
- package/dist/types/duckduckgo-rate-limit.d.ts +52 -0
- package/dist/types/duckduckgo.d.ts +6 -0
- package/dist/types/endpoint-pdf-extract.d.ts +22 -0
- package/dist/types/exa.d.ts +17 -0
- package/dist/types/extract.d.ts +70 -0
- package/dist/types/feature-config.d.ts +2 -0
- package/dist/types/fetch-params.d.ts +39 -0
- package/dist/types/field-extract.d.ts +37 -0
- package/dist/types/firecrawl.d.ts +18 -0
- package/dist/types/gemini-adc.d.ts +9 -0
- package/dist/types/gemini-api.d.ts +37 -0
- package/dist/types/gemini-pdf-extract.d.ts +8 -0
- package/dist/types/gemini-search.d.ts +76 -0
- package/dist/types/gemini-url-context.d.ts +3 -0
- package/dist/types/gemini-web-config.d.ts +25 -0
- package/dist/types/gemini-web.d.ts +31 -0
- package/dist/types/github-api.d.ts +6 -0
- package/dist/types/github-extract.d.ts +19 -0
- package/dist/types/github-issue-pr.d.ts +28 -0
- package/dist/types/index.d.ts +53 -0
- package/dist/types/jina-search.d.ts +7 -0
- package/dist/types/kagi.d.ts +14 -0
- package/dist/types/keenable.d.ts +3 -0
- package/dist/types/kimi-search.d.ts +4 -0
- package/dist/types/linkup.d.ts +5 -0
- package/dist/types/mcp-cli.d.ts +2 -0
- package/dist/types/mcp-server.d.ts +10 -0
- package/dist/types/mcp-tool-definitions.d.ts +16 -0
- package/dist/types/mistral-search.d.ts +3 -0
- package/dist/types/ninerouter.d.ts +3 -0
- package/dist/types/offtopic-judge.d.ts +26 -0
- package/dist/types/ollama.d.ts +14 -0
- package/dist/types/openai-search.d.ts +23 -0
- package/dist/types/page-query.d.ts +22 -0
- package/dist/types/parallel-mcp.d.ts +10 -0
- package/dist/types/parallel.d.ts +13 -0
- package/dist/types/pdf-extract.d.ts +44 -0
- package/dist/types/perplexity.d.ts +26 -0
- package/dist/types/pi-mcp.d.ts +56 -0
- package/dist/types/pi-session-results.d.ts +8 -0
- package/dist/types/querit.d.ts +9 -0
- package/dist/types/query-rewrite.d.ts +2 -0
- package/dist/types/render-search-error.d.ts +56 -0
- package/dist/types/retrieval-only.d.ts +78 -0
- package/dist/types/rsc-extract.d.ts +11 -0
- package/dist/types/search-answer-formatting.d.ts +7 -0
- package/dist/types/search-result-count-normalization.d.ts +1 -0
- package/dist/types/searchinfinity.d.ts +7 -0
- package/dist/types/searxng.d.ts +3 -0
- package/dist/types/source-check.d.ts +102 -0
- package/dist/types/ssrf-protection.d.ts +66 -0
- package/dist/types/storage.d.ts +69 -0
- package/dist/types/summary-model-scope.d.ts +33 -0
- package/dist/types/summary-review.d.ts +30 -0
- package/dist/types/tabstack.d.ts +5 -0
- package/dist/types/tavily.d.ts +7 -0
- package/dist/types/tinyfish.d.ts +10 -0
- package/dist/types/tool-activation.d.ts +7 -0
- package/dist/types/tool-arguments.d.ts +1 -0
- package/dist/types/upgrade-notice.d.ts +6 -0
- package/dist/types/utils.d.ts +55 -0
- package/dist/types/valyu.d.ts +5 -0
- package/dist/types/video-extract.d.ts +15 -0
- package/dist/types/web-tool-contract.d.ts +98 -0
- package/dist/types/web-tool-core.d.ts +227 -0
- package/dist/types/xai-search.d.ts +12 -0
- package/dist/types/you.d.ts +3 -0
- package/dist/types/youtube-extract.d.ts +29 -0
- package/dist/types/zai.d.ts +3 -0
- package/docs/pi-mcp.md +41 -0
- package/domain-filter-normalization.ts +44 -0
- package/duckduckgo-rate-limit.ts +205 -0
- package/duckduckgo.ts +123 -0
- package/endpoint-pdf-extract.ts +225 -0
- package/exa.ts +620 -0
- package/extract.ts +1721 -0
- package/feature-config.ts +29 -0
- package/fetch-params.ts +147 -0
- package/field-extract.ts +347 -0
- package/firecrawl.ts +476 -0
- package/gemini-adc.ts +345 -0
- package/gemini-api.ts +368 -0
- package/gemini-pdf-extract.ts +108 -0
- package/gemini-search.ts +1162 -0
- package/gemini-url-context.ts +128 -0
- package/gemini-web-config.ts +131 -0
- package/gemini-web.ts +527 -0
- package/github-api.ts +197 -0
- package/github-extract.ts +1064 -0
- package/github-issue-pr.ts +717 -0
- package/index.ts +2819 -0
- package/jina-search.ts +275 -0
- package/kagi.ts +257 -0
- package/keenable.ts +222 -0
- package/kimi-search.ts +209 -0
- package/linkup.ts +170 -0
- package/mcp-cli.ts +40 -0
- package/mcp-server.ts +84 -0
- package/mcp-tool-definitions.ts +143 -0
- package/mistral-search.ts +268 -0
- package/ninerouter.ts +92 -0
- package/offtopic-judge.ts +72 -0
- package/ollama.ts +237 -0
- package/openai-search.ts +855 -0
- package/package.json +108 -4
- package/page-query.ts +185 -0
- package/parallel-mcp.ts +255 -0
- package/parallel.ts +373 -0
- package/pdf-extract.ts +447 -0
- package/perplexity.ts +245 -0
- package/pi-mcp.ts +139 -0
- package/pi-session-results.ts +40 -0
- package/pi-web-fetch-demo.mp4 +0 -0
- package/promise-try.d.ts +7 -0
- package/querit.ts +394 -0
- package/query-rewrite.ts +84 -0
- package/render-search-error.ts +170 -0
- package/retrieval-only.ts +102 -0
- package/rsc-extract.ts +338 -0
- package/search-answer-formatting.ts +11 -0
- package/search-result-count-normalization.ts +4 -0
- package/searchinfinity.ts +246 -0
- package/searxng.ts +236 -0
- package/source-check.ts +269 -0
- package/ssrf-protection.ts +602 -0
- package/storage.ts +547 -0
- package/summary-model-scope.ts +72 -0
- package/summary-review.ts +476 -0
- package/tabstack.ts +289 -0
- package/tavily.ts +257 -0
- package/tinyfish.ts +373 -0
- package/tool-activation.ts +169 -0
- package/tool-arguments.ts +23 -0
- package/upgrade-notice.ts +47 -0
- package/utils.ts +693 -0
- package/valyu.ts +177 -0
- package/video-extract.ts +398 -0
- package/web-tool-contract.ts +93 -0
- package/web-tool-core.ts +1810 -0
- package/xai-search.ts +443 -0
- package/you.ts +165 -0
- package/youtube-extract.ts +336 -0
- package/zai.ts +161 -0
package/extract.ts
ADDED
|
@@ -0,0 +1,1721 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import type TurndownService from "turndown";
|
|
3
|
+
import pLimit from "p-limit";
|
|
4
|
+
import { activityMonitor } from "./activity.ts";
|
|
5
|
+
import { extractRSCContent } from "./rsc-extract.ts";
|
|
6
|
+
import { extractPDFToMarkdown, isPDF, loadPDFConfig } from "./pdf-extract.ts";
|
|
7
|
+
import { extractGitHub, parseGitHubUrl } from "./github-extract.ts";
|
|
8
|
+
import { extractGitHubIssuePr, parseGitHubIssuePrUrl } from "./github-issue-pr.ts";
|
|
9
|
+
import { isYouTubeURL, isYouTubeEnabled, extractYouTube, extractYouTubeFrame, extractYouTubeFrames, getYouTubeStreamInfo, youTubeAccessError } from "./youtube-extract.ts";
|
|
10
|
+
import { CredentialResolutionError } from "./credential-source.ts";
|
|
11
|
+
import { extractWithUrlContext, extractWithGeminiWeb } from "./gemini-url-context.ts";
|
|
12
|
+
import { browserCookieAccessHint, browserCookieAccessHintLine } from "./gemini-web.ts";
|
|
13
|
+
import type { BrowserCookieConsent } from "./gemini-web-config.ts";
|
|
14
|
+
import { extractWithParallel, isParallelAvailable } from "./parallel.ts";
|
|
15
|
+
import { extractWithParallelMcp } from "./parallel-mcp.ts";
|
|
16
|
+
import { extractWithTinyFish, isTinyFishAvailable } from "./tinyfish.ts";
|
|
17
|
+
import { extractWithDeepSeek, isDeepSeekAvailable } from "./deepseek.ts";
|
|
18
|
+
import { extractWithExa, hasExaApiKey } from "./exa.ts";
|
|
19
|
+
import { extractWithQuerit, isQueritAvailable } from "./querit.ts";
|
|
20
|
+
import { extractWithTabstack, isTabstackAvailable } from "./tabstack.ts";
|
|
21
|
+
import { extractWithKagi, isKagiExtractAvailable } from "./kagi.ts";
|
|
22
|
+
import { extractWithOllama, isOllamaFetchAvailable } from "./ollama.ts";
|
|
23
|
+
import { extractWithFirecrawl, isFirecrawlAvailable } from "./firecrawl.ts";
|
|
24
|
+
import { extractWithCrawl4ai, isCrawl4aiAvailable } from "./crawl4ai.ts";
|
|
25
|
+
import { extractWithBrightDataUnlocker, isBrightDataUnlockerAvailable } from "./brightdata-unlocker.ts";
|
|
26
|
+
import { isVideoFile, extractVideo, extractVideoFrame, getLocalVideoDuration } from "./video-extract.ts";
|
|
27
|
+
import { appendDeclaredWebLinks, discoverDeclaredWebLinks, type DeclaredWebLink } from "./declared-web-links.ts";
|
|
28
|
+
import { fetchRemoteUrl, loadConfiguredFetchContentUserAgent, loadFetchContentCurl, loadFetchContentDomainPolicy, loadFetchContentRedirectPolicy, loadFetchContentUserAgent, loadSsrfConfig, trustedEnvProxyFor, validateRemoteUrl, type DomainPolicy, type Lookup, type RedirectPolicy, type SsrfConfig } from "./ssrf-protection.ts";
|
|
29
|
+
import { createCurlFetch, formatSeconds, getWebSearchConfigPath, type ProxiedRequestInit } from "./utils.ts";
|
|
30
|
+
import { FETCH_PROVIDER_KINDS, getRetrievalOnlyPolicy, retrievalOnlyExhaustedError } from "./retrieval-only.ts";
|
|
31
|
+
import { isImageEnabled } from "./feature-config.ts";
|
|
32
|
+
import { assertAuthFetchUrl, authFetchRedirectGuard, type AuthFetchProfile } from "./auth-fetch.ts";
|
|
33
|
+
import { getBrowserCookiesForHosts, getLastBrowserCookieDiagnostic } from "./chrome-cookies.ts";
|
|
34
|
+
import { sanitizeInlineDataUris } from "./data-uri-sanitize.ts";
|
|
35
|
+
|
|
36
|
+
const DEFAULT_TIMEOUT_MS = 30000;
|
|
37
|
+
const MAX_CONFIGURED_TIMEOUT_MS = 2_147_483_647;
|
|
38
|
+
const CONCURRENT_LIMIT = 3;
|
|
39
|
+
const WEB_SEARCH_CONFIG_PATH = getWebSearchConfigPath();
|
|
40
|
+
|
|
41
|
+
function loadFetchTimeoutMs(): number {
|
|
42
|
+
if (!existsSync(WEB_SEARCH_CONFIG_PATH)) return DEFAULT_TIMEOUT_MS;
|
|
43
|
+
|
|
44
|
+
let raw: unknown;
|
|
45
|
+
try {
|
|
46
|
+
raw = JSON.parse(readFileSync(WEB_SEARCH_CONFIG_PATH, "utf-8"));
|
|
47
|
+
} catch (err) {
|
|
48
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
49
|
+
throw new Error(`Failed to parse ${WEB_SEARCH_CONFIG_PATH}: ${message}`);
|
|
50
|
+
}
|
|
51
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
52
|
+
throw new Error(`Invalid config in ${WEB_SEARCH_CONFIG_PATH}: expected a JSON object`);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const fetchConfig = (raw as Record<string, unknown>).fetch;
|
|
56
|
+
if (fetchConfig === undefined) return DEFAULT_TIMEOUT_MS;
|
|
57
|
+
if (!fetchConfig || typeof fetchConfig !== "object" || Array.isArray(fetchConfig)) {
|
|
58
|
+
throw new Error(`fetch in ${WEB_SEARCH_CONFIG_PATH} must be an object`);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const value = (fetchConfig as Record<string, unknown>).timeout;
|
|
62
|
+
if (value === undefined) return DEFAULT_TIMEOUT_MS;
|
|
63
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
64
|
+
throw new Error(`Invalid fetch.timeout in ${WEB_SEARCH_CONFIG_PATH}: expected a positive finite number of seconds, got ${JSON.stringify(value)}`);
|
|
65
|
+
}
|
|
66
|
+
const timeoutMs = Math.ceil(value * 1000);
|
|
67
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > MAX_CONFIGURED_TIMEOUT_MS) {
|
|
68
|
+
throw new Error(`Invalid fetch.timeout in ${WEB_SEARCH_CONFIG_PATH}: converted timeout must be a finite safe integer from 1 through ${MAX_CONFIGURED_TIMEOUT_MS} milliseconds`);
|
|
69
|
+
}
|
|
70
|
+
return Math.max(1, timeoutMs);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const NON_RECOVERABLE_ERRORS = ["Unsupported content type", "Response too large", "PDF extraction is disabled", "Image fetching is disabled", "fetchContent.curl command not found"];
|
|
74
|
+
const MIN_USEFUL_CONTENT = 500;
|
|
75
|
+
const SUPPORTED_IMAGE_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
|
|
76
|
+
export const FETCH_PROVIDERS = ["http", "firecrawl", "crawl4ai", "jina", "tinyfish", "querit", "kagi", "ollama", "parallel", "parallel-mcp", "brightdata", "gemini", "deepseek", "exa", "tabstack"] as const;
|
|
77
|
+
const REMOVED_FETCH_PROVIDERS = ["search1api", "specstream"];
|
|
78
|
+
export type FetchProvider = typeof FETCH_PROVIDERS[number];
|
|
79
|
+
type FetchRouting = { providers: FetchProvider[]; allowRemoteHostedProviders: boolean };
|
|
80
|
+
const DEFAULT_FETCH_PROVIDER_ORDER: FetchProvider[] = ["http", "firecrawl", "crawl4ai", "jina", "tinyfish", "querit", "kagi", "ollama", "parallel", "brightdata", "gemini"];
|
|
81
|
+
const REMOTE_HOSTED_FETCH_PROVIDERS = new Set<FetchProvider>(["jina", "tinyfish", "querit", "kagi", "ollama", "parallel", "parallel-mcp", "brightdata", "gemini", "deepseek", "exa", "tabstack"]);
|
|
82
|
+
|
|
83
|
+
function isDefuddleConsoleError(args: Parameters<typeof console.error>): boolean {
|
|
84
|
+
const prefix = args[0];
|
|
85
|
+
return prefix === "Defuddle" || (typeof prefix === "string" && /^Defuddle(?:\s|:)/.test(prefix));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function extractWithDefuddle(text: string, url: string): Promise<{ title: string; content: string } | null> {
|
|
89
|
+
const { Defuddle } = await import("defuddle/node");
|
|
90
|
+
const { parseHTML } = await import("linkedom");
|
|
91
|
+
const { document } = parseHTML(text);
|
|
92
|
+
Object.defineProperty(document, "location", {
|
|
93
|
+
value: new URL(url),
|
|
94
|
+
configurable: true,
|
|
95
|
+
});
|
|
96
|
+
let processingError: unknown;
|
|
97
|
+
const originalConsoleError = console.error;
|
|
98
|
+
console.error = (...args) => {
|
|
99
|
+
if (isDefuddleConsoleError(args)) {
|
|
100
|
+
if (args[0] === "Defuddle" && args[1] === "Error processing document:") {
|
|
101
|
+
processingError = args[2];
|
|
102
|
+
}
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
originalConsoleError(...args);
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
let resultPromise: ReturnType<typeof Defuddle>;
|
|
109
|
+
try {
|
|
110
|
+
// With useAsync:false, Defuddle parses synchronously before returning its promise.
|
|
111
|
+
// Keep the console interception limited to that call so unrelated Pi output is
|
|
112
|
+
// never routed through this fallback's handler.
|
|
113
|
+
resultPromise = Defuddle(document as unknown as Document, url, { markdown: true, useAsync: false });
|
|
114
|
+
} finally {
|
|
115
|
+
console.error = originalConsoleError;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const result = await resultPromise;
|
|
119
|
+
if (processingError !== undefined) {
|
|
120
|
+
throw new Error(`Defuddle failed to process document: ${errorMessage(processingError)}`);
|
|
121
|
+
}
|
|
122
|
+
return typeof result.content === "string" ? { title: result.title, content: result.content } : null;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export { loadSsrfConfig } from "./ssrf-protection.ts";
|
|
126
|
+
|
|
127
|
+
export function loadSsrfAllowRanges(): string[] {
|
|
128
|
+
return loadSsrfConfig().allowRanges;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function errorMessage(err: unknown): string {
|
|
132
|
+
return err instanceof Error ? err.message : String(err);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function isConfigParseError(err: unknown): boolean {
|
|
136
|
+
return errorMessage(err).startsWith("Failed to parse ");
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function isAbortError(err: unknown): boolean {
|
|
140
|
+
return errorMessage(err).toLowerCase().includes("abort");
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function isAbortException(err: unknown): boolean {
|
|
144
|
+
return err instanceof DOMException && (err.name === "AbortError" || err.name === "TimeoutError");
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function isRedirectPolicyError(message: string): boolean {
|
|
148
|
+
return message.startsWith("Authenticated fetch refused cross-origin redirect") ||
|
|
149
|
+
message.startsWith("Refused cross-origin redirect by fetch_content redirect policy") ||
|
|
150
|
+
message.startsWith("Blocked internal ") ||
|
|
151
|
+
message.startsWith("Blocked hostname by fetch_content domain policy") ||
|
|
152
|
+
message.startsWith("Hostname not allowed by fetch_content domain policy") ||
|
|
153
|
+
message.startsWith("Too many redirects fetching ") ||
|
|
154
|
+
message === "Only HTTP and HTTPS URLs can be fetched remotely" ||
|
|
155
|
+
message === "URL must include a hostname" ||
|
|
156
|
+
message.startsWith("Failed to resolve ");
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Errors that end routing: no other provider may be tried after them.
|
|
160
|
+
function isNonRecoverableHttpError(error: string | null): boolean {
|
|
161
|
+
return !!error && (NON_RECOVERABLE_ERRORS.some(prefix => error.startsWith(prefix)) ||
|
|
162
|
+
isRedirectPolicyError(error) || isConfigParseError(error));
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function imageGateError(): string | null {
|
|
166
|
+
try {
|
|
167
|
+
return isImageEnabled() ? null : "Image fetching is disabled by image.enabled";
|
|
168
|
+
} catch (err) {
|
|
169
|
+
return errorMessage(err);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function redirectPolicyRouteRefusal(url: string, path: string): ExtractedContent {
|
|
174
|
+
return { url, title: "", content: "", error: `Extraction path ${path} is disabled by the fetch_content same-origin redirect policy because its redirect chain cannot be observed` };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async function resolveAuthCookieHeader(url: string | URL, profile: AuthFetchProfile): Promise<string> {
|
|
178
|
+
const parsed = assertAuthFetchUrl(profile, url.toString());
|
|
179
|
+
const result = await getBrowserCookiesForHosts({ hosts: [parsed.hostname], browser: profile.browser, profile: profile.chromeProfile, requestUrl: parsed });
|
|
180
|
+
if (result?.cookieHeader) return result.cookieHeader;
|
|
181
|
+
if (!result) {
|
|
182
|
+
const diagnostic = getLastBrowserCookieDiagnostic();
|
|
183
|
+
throw new Error(`Authenticated fetch profile ${profile.name} could not read browser cookies${diagnostic ? `: ${diagnostic}` : ""}`);
|
|
184
|
+
}
|
|
185
|
+
throw new Error(`Authenticated fetch profile ${profile.name} could not build a cookie header`);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
|
|
189
|
+
|
|
190
|
+
async function fetchAuthenticatedRemoteUrl(
|
|
191
|
+
url: string,
|
|
192
|
+
init: RequestInit,
|
|
193
|
+
validationOptions: { ssrf: SsrfConfig; domainPolicy: DomainPolicy; lookup?: Lookup; proxy?: string; redirects?: RedirectPolicy },
|
|
194
|
+
profile: AuthFetchProfile,
|
|
195
|
+
): Promise<Response> {
|
|
196
|
+
let current = await validateRemoteUrl(url, {
|
|
197
|
+
allowRanges: validationOptions.ssrf.allowRanges,
|
|
198
|
+
trustEnvProxy: validationOptions.ssrf.trustEnvProxy,
|
|
199
|
+
domainPolicy: validationOptions.domainPolicy,
|
|
200
|
+
proxy: validationOptions.proxy,
|
|
201
|
+
...(validationOptions.lookup ? { lookup: validationOptions.lookup } : {}),
|
|
202
|
+
});
|
|
203
|
+
const originalOrigin = current.origin;
|
|
204
|
+
let requestInit = init;
|
|
205
|
+
for (let redirects = 0; redirects <= 5; redirects++) {
|
|
206
|
+
const cookieHeader = await resolveAuthCookieHeader(current, profile);
|
|
207
|
+
const headers = { ...(requestInit.headers as Record<string, string>), cookie: cookieHeader };
|
|
208
|
+
const response = await fetch(current, { ...requestInit, headers, redirect: "manual" });
|
|
209
|
+
if (!REDIRECT_STATUSES.has(response.status)) return response;
|
|
210
|
+
const location = response.headers.get("location");
|
|
211
|
+
if (!location) return response;
|
|
212
|
+
if (redirects === 5) throw new Error(`Too many redirects fetching ${current.toString()}`);
|
|
213
|
+
const from = current;
|
|
214
|
+
const next = new URL(location, current);
|
|
215
|
+
if (validationOptions.redirects === "same-origin" && next.origin !== originalOrigin) {
|
|
216
|
+
throw new Error(`Refused cross-origin redirect by fetch_content redirect policy: ${originalOrigin} -> ${next.origin}`);
|
|
217
|
+
}
|
|
218
|
+
current = await validateRemoteUrl(next, {
|
|
219
|
+
allowRanges: validationOptions.ssrf.allowRanges,
|
|
220
|
+
trustEnvProxy: validationOptions.ssrf.trustEnvProxy,
|
|
221
|
+
domainPolicy: validationOptions.domainPolicy,
|
|
222
|
+
proxy: validationOptions.proxy,
|
|
223
|
+
...(validationOptions.lookup ? { lookup: validationOptions.lookup } : {}),
|
|
224
|
+
});
|
|
225
|
+
authFetchRedirectGuard(profile, from, current);
|
|
226
|
+
if (response.status === 303 || ((response.status === 301 || response.status === 302) && requestInit.method?.toUpperCase() === "POST")) {
|
|
227
|
+
const { body: _body, ...nextInit } = requestInit;
|
|
228
|
+
requestInit = { ...nextInit, method: "GET" };
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
throw new Error(`Too many redirects fetching ${current.toString()}`);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function loadFetchRouting(): FetchRouting {
|
|
235
|
+
if (!existsSync(WEB_SEARCH_CONFIG_PATH)) {
|
|
236
|
+
return { providers: DEFAULT_FETCH_PROVIDER_ORDER, allowRemoteHostedProviders: false };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
let raw: Record<string, unknown>;
|
|
240
|
+
try {
|
|
241
|
+
const parsed: unknown = JSON.parse(readFileSync(WEB_SEARCH_CONFIG_PATH, "utf-8"));
|
|
242
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
243
|
+
throw new Error("expected a JSON object");
|
|
244
|
+
}
|
|
245
|
+
raw = parsed as Record<string, unknown>;
|
|
246
|
+
} catch (err) {
|
|
247
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
248
|
+
throw new Error(`Failed to parse ${WEB_SEARCH_CONFIG_PATH}: ${message}`);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
if (!Object.hasOwn(raw, "fetchRouting")) {
|
|
252
|
+
return { providers: DEFAULT_FETCH_PROVIDER_ORDER, allowRemoteHostedProviders: false };
|
|
253
|
+
}
|
|
254
|
+
const routing = raw.fetchRouting;
|
|
255
|
+
if (!routing || typeof routing !== "object" || Array.isArray(routing)) {
|
|
256
|
+
throw new Error(`fetchRouting in ${WEB_SEARCH_CONFIG_PATH} must be an object`);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const routingConfig = routing as Record<string, unknown>;
|
|
260
|
+
const providersValue = routingConfig.providers;
|
|
261
|
+
let providers = DEFAULT_FETCH_PROVIDER_ORDER;
|
|
262
|
+
if (providersValue !== undefined) {
|
|
263
|
+
if (!Array.isArray(providersValue) || providersValue.length === 0) {
|
|
264
|
+
throw new Error(`fetchRouting.providers in ${WEB_SEARCH_CONFIG_PATH} must be a non-empty array`);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
providers = [];
|
|
268
|
+
for (const provider of providersValue) {
|
|
269
|
+
const normalized = typeof provider === "string" ? provider.trim().toLowerCase() : "";
|
|
270
|
+
if (REMOVED_FETCH_PROVIDERS.includes(normalized)) {
|
|
271
|
+
throw new Error(`fetchRouting.providers in ${WEB_SEARCH_CONFIG_PATH} lists ${normalized}, which was removed as a fetch provider; remove it from fetchRouting.providers`);
|
|
272
|
+
}
|
|
273
|
+
if (!FETCH_PROVIDERS.includes(normalized as FetchProvider)) {
|
|
274
|
+
throw new Error(`fetchRouting.providers in ${WEB_SEARCH_CONFIG_PATH} contains an invalid provider: ${String(provider)}`);
|
|
275
|
+
}
|
|
276
|
+
if (providers.includes(normalized as FetchProvider)) {
|
|
277
|
+
throw new Error(`fetchRouting.providers in ${WEB_SEARCH_CONFIG_PATH} must not contain duplicates: ${normalized}`);
|
|
278
|
+
}
|
|
279
|
+
providers.push(normalized as FetchProvider);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const allowRemoteHostedProvidersValue = routingConfig.allowRemoteHostedProviders;
|
|
284
|
+
if (allowRemoteHostedProvidersValue !== undefined && typeof allowRemoteHostedProvidersValue !== "boolean") {
|
|
285
|
+
throw new Error(`fetchRouting.allowRemoteHostedProviders in ${WEB_SEARCH_CONFIG_PATH} must be a boolean`);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
return { providers, allowRemoteHostedProviders: allowRemoteHostedProvidersValue === true };
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Names of the search/fetch tools the caller has actually registered, so
|
|
292
|
+
* failure guidance never points at tools that do not exist in the session. */
|
|
293
|
+
export interface RegisteredToolNames {
|
|
294
|
+
webSearch?: string;
|
|
295
|
+
fetchContent?: string;
|
|
296
|
+
getSearchContent?: string;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Guidance for definitive origin 404/410 responses: no extraction provider
|
|
300
|
+
* can retrieve a page the origin says is gone, so point at the registered
|
|
301
|
+
* search/fetch tools (when the caller knows them) instead of provider config. */
|
|
302
|
+
function notFoundGuidance(result: ExtractedContent, toolNames?: RegisteredToolNames): string {
|
|
303
|
+
const lines = [
|
|
304
|
+
result.error ?? `HTTP ${result.status}`,
|
|
305
|
+
"",
|
|
306
|
+
`The origin server says this page does not exist (HTTP ${result.status}), so extraction providers cannot retrieve it.`,
|
|
307
|
+
];
|
|
308
|
+
if (toolNames?.webSearch && toolNames.fetchContent) {
|
|
309
|
+
lines.push(`The page may have moved or been renamed. Use ${toolNames.webSearch} to find the current URL, then retry ${toolNames.fetchContent} with it.`);
|
|
310
|
+
} else if (toolNames?.webSearch) {
|
|
311
|
+
lines.push(`The page may have moved or been renamed. Use ${toolNames.webSearch} to find the current URL.`);
|
|
312
|
+
} else {
|
|
313
|
+
lines.push("The page may have moved or been renamed. Find the current URL, then retry the fetch with it.");
|
|
314
|
+
}
|
|
315
|
+
return lines.join("\n");
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
/** Fallback-list hint for the keyless Jina Reader. Returns null when Jina
|
|
320
|
+
* already ran for this fetch, and otherwise names only the config change still
|
|
321
|
+
* missing, so users keep their existing or default provider order. */
|
|
322
|
+
function jinaReaderGuidance(routing: FetchRouting, providerOrder: FetchProvider[], needsRemoteOptIn: boolean): string | null {
|
|
323
|
+
if (providerOrder.includes("jina")) return null;
|
|
324
|
+
const privacy = "target URLs are fetched through Jina's infrastructure";
|
|
325
|
+
const optInCaveat = "this also allows the other hosted providers in your fetch provider order";
|
|
326
|
+
if (routing.providers.includes("jina")) {
|
|
327
|
+
return ` • Enable the keyless Jina Reader fallback: set fetchRouting.allowRemoteHostedProviders to true in ${WEB_SEARCH_CONFIG_PATH} (Jina is already in your fetch provider order; ${optInCaveat}; ${privacy})`;
|
|
328
|
+
}
|
|
329
|
+
return needsRemoteOptIn
|
|
330
|
+
? ` • Enable the keyless Jina Reader fallback: add "jina" to your existing fetchRouting.providers and set fetchRouting.allowRemoteHostedProviders to true in ${WEB_SEARCH_CONFIG_PATH} (${optInCaveat}; ${privacy})`
|
|
331
|
+
: ` • Enable the keyless Jina Reader fallback: add "jina" to your existing fetchRouting.providers in ${WEB_SEARCH_CONFIG_PATH} (${privacy})`;
|
|
332
|
+
}
|
|
333
|
+
function abortedResult(url: string): ExtractedContent {
|
|
334
|
+
return { url, title: "", content: "", error: "Aborted" };
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// Share first-use initialization without loading Turndown at extension startup.
|
|
338
|
+
let turndownInstance: Promise<TurndownService> | undefined;
|
|
339
|
+
async function loadTurndown(): Promise<TurndownService> {
|
|
340
|
+
const { default: TurndownService } = await import("turndown");
|
|
341
|
+
return new TurndownService({
|
|
342
|
+
headingStyle: "atx",
|
|
343
|
+
codeBlockStyle: "fenced",
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
function getTurndown(): Promise<TurndownService> {
|
|
347
|
+
turndownInstance ??= loadTurndown();
|
|
348
|
+
return turndownInstance;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const fetchLimit = pLimit(CONCURRENT_LIMIT);
|
|
352
|
+
|
|
353
|
+
export interface VideoFrame {
|
|
354
|
+
data: string;
|
|
355
|
+
mimeType: string;
|
|
356
|
+
timestamp: string;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
export type FrameData = { data: string; mimeType: string };
|
|
360
|
+
export type FrameResult = FrameData | { error: string };
|
|
361
|
+
|
|
362
|
+
export interface ExtractedContent {
|
|
363
|
+
url: string;
|
|
364
|
+
title: string;
|
|
365
|
+
content: string;
|
|
366
|
+
error: string | null;
|
|
367
|
+
thumbnail?: { data: string; mimeType: string };
|
|
368
|
+
frames?: VideoFrame[];
|
|
369
|
+
duration?: number;
|
|
370
|
+
mimeType?: string;
|
|
371
|
+
status?: number;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
type HttpExtractedContent = ExtractedContent & { declaredLinks?: DeclaredWebLink[] };
|
|
375
|
+
|
|
376
|
+
export interface ExtractOptions {
|
|
377
|
+
timeoutMs?: number;
|
|
378
|
+
forceClone?: boolean;
|
|
379
|
+
prompt?: string;
|
|
380
|
+
timestamp?: string;
|
|
381
|
+
frames?: number;
|
|
382
|
+
model?: string;
|
|
383
|
+
mode?: "readable" | "raw" | "answer" | "extract";
|
|
384
|
+
answerModel?: string;
|
|
385
|
+
authFetchProfile?: AuthFetchProfile;
|
|
386
|
+
toolNames?: RegisteredToolNames;
|
|
387
|
+
/** Optional HTTP(S) or SOCKS proxy URL; routed through the curl-backed transport. */
|
|
388
|
+
proxy?: string;
|
|
389
|
+
/** Reject direct image URLs with this error instead of decoding them with Pi's
|
|
390
|
+
* resizeImage. Hosts without the Pi runtime set it; Pi leaves it unset. */
|
|
391
|
+
rejectDirectImages?: string;
|
|
392
|
+
/** Custom DNS resolver used for SSRF validation. Primarily a test seam. */
|
|
393
|
+
lookup?: Lookup;
|
|
394
|
+
/** "same-origin" refuses cross-origin redirects and extraction paths whose redirect
|
|
395
|
+
* chain cannot be observed. fetchContent.redirects in config is a floor. */
|
|
396
|
+
redirects?: RedirectPolicy;
|
|
397
|
+
/** Lets video analysis ask the user to turn on browser cookie access for Gemini Web. */
|
|
398
|
+
browserCookieConsent?: BrowserCookieConsent;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** Resolve the direct HTTP/Jina fetch budget, with a per-call override taking precedence. */
|
|
402
|
+
export function resolveFetchTimeoutMs(options?: Pick<ExtractOptions, "timeoutMs">): number {
|
|
403
|
+
return options?.timeoutMs ?? loadFetchTimeoutMs();
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
const JINA_READER_BASE = "https://r.jina.ai/";
|
|
407
|
+
|
|
408
|
+
async function extractWithJinaReader(
|
|
409
|
+
url: string,
|
|
410
|
+
timeoutMs: number,
|
|
411
|
+
signal?: AbortSignal,
|
|
412
|
+
lookup?: Lookup,
|
|
413
|
+
): Promise<ExtractedContent | null> {
|
|
414
|
+
const jinaUrl = JINA_READER_BASE + url;
|
|
415
|
+
|
|
416
|
+
const activityId = activityMonitor.logStart({ type: "api", query: `jina: ${url}` });
|
|
417
|
+
|
|
418
|
+
try {
|
|
419
|
+
const ssrf = loadSsrfConfig();
|
|
420
|
+
const domainPolicy = loadFetchContentDomainPolicy();
|
|
421
|
+
await validateRemoteUrl(url, {
|
|
422
|
+
allowRanges: ssrf.allowRanges,
|
|
423
|
+
trustEnvProxy: ssrf.trustEnvProxy,
|
|
424
|
+
domainPolicy,
|
|
425
|
+
...(lookup ? { lookup } : {}),
|
|
426
|
+
});
|
|
427
|
+
const res = await fetch(jinaUrl, {
|
|
428
|
+
headers: {
|
|
429
|
+
"Accept": "text/markdown",
|
|
430
|
+
"X-No-Cache": "true",
|
|
431
|
+
},
|
|
432
|
+
signal: AbortSignal.any([
|
|
433
|
+
AbortSignal.timeout(timeoutMs),
|
|
434
|
+
...(signal ? [signal] : []),
|
|
435
|
+
]),
|
|
436
|
+
});
|
|
437
|
+
|
|
438
|
+
if (!res.ok) {
|
|
439
|
+
activityMonitor.logComplete(activityId, res.status);
|
|
440
|
+
return null;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
const content = await res.text();
|
|
444
|
+
activityMonitor.logComplete(activityId, res.status);
|
|
445
|
+
|
|
446
|
+
const contentStart = content.indexOf("Markdown Content:");
|
|
447
|
+
if (contentStart < 0) {
|
|
448
|
+
return null;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
const markdownPart = content.slice(contentStart + 17).trim(); // 17 = "Markdown Content:".length
|
|
452
|
+
|
|
453
|
+
// Check for failed JS rendering or minimal content
|
|
454
|
+
if (markdownPart.length < 100 ||
|
|
455
|
+
markdownPart.startsWith("Loading...") ||
|
|
456
|
+
markdownPart.startsWith("Please enable JavaScript")) {
|
|
457
|
+
return null;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
const title = extractHeadingTitle(markdownPart) ?? (new URL(url).pathname.split("/").pop() || url);
|
|
461
|
+
return { url, title, content: markdownPart, error: null };
|
|
462
|
+
} catch (err) {
|
|
463
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
464
|
+
if (message.toLowerCase().includes("abort")) {
|
|
465
|
+
activityMonitor.logComplete(activityId, 0);
|
|
466
|
+
} else {
|
|
467
|
+
activityMonitor.logError(activityId, message);
|
|
468
|
+
}
|
|
469
|
+
return null;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function parseTimestamp(ts: string): number | null {
|
|
474
|
+
const num = Number(ts);
|
|
475
|
+
if (!isNaN(num) && num >= 0) return Math.floor(num);
|
|
476
|
+
const parts = ts.split(":").map(Number);
|
|
477
|
+
if (parts.some(p => isNaN(p) || p < 0)) return null;
|
|
478
|
+
if (parts.length === 3) return Math.floor(parts[0] * 3600 + parts[1] * 60 + parts[2]);
|
|
479
|
+
if (parts.length === 2) return Math.floor(parts[0] * 60 + parts[1]);
|
|
480
|
+
return null;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
type TimestampSpec = { type: "single"; seconds: number } | { type: "range"; start: number; end: number };
|
|
484
|
+
|
|
485
|
+
function parseTimestampSpec(ts: string): TimestampSpec | null {
|
|
486
|
+
const dashIdx = ts.indexOf("-", 1);
|
|
487
|
+
if (dashIdx > 0) {
|
|
488
|
+
const start = parseTimestamp(ts.slice(0, dashIdx));
|
|
489
|
+
const end = parseTimestamp(ts.slice(dashIdx + 1));
|
|
490
|
+
if (start !== null && end !== null && end > start) return { type: "range", start, end };
|
|
491
|
+
}
|
|
492
|
+
const seconds = parseTimestamp(ts);
|
|
493
|
+
return seconds !== null ? { type: "single", seconds } : null;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
const DEFAULT_RANGE_FRAMES = 6;
|
|
497
|
+
const MIN_FRAME_INTERVAL = 5;
|
|
498
|
+
|
|
499
|
+
function computeRangeTimestamps(start: number, end: number, maxFrames: number = DEFAULT_RANGE_FRAMES): number[] {
|
|
500
|
+
if (maxFrames <= 1) return [start];
|
|
501
|
+
const duration = end - start;
|
|
502
|
+
const idealInterval = duration / (maxFrames - 1);
|
|
503
|
+
if (idealInterval < MIN_FRAME_INTERVAL) {
|
|
504
|
+
const timestamps: number[] = [];
|
|
505
|
+
for (let t = start; t <= end && timestamps.length < maxFrames; t += MIN_FRAME_INTERVAL) {
|
|
506
|
+
timestamps.push(t);
|
|
507
|
+
}
|
|
508
|
+
return timestamps;
|
|
509
|
+
}
|
|
510
|
+
return Array.from({ length: maxFrames }, (_, i) => Math.round(start + i * idealInterval));
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function buildFrameResult(
|
|
514
|
+
url: string, label: string, requestedCount: number,
|
|
515
|
+
frames: VideoFrame[], error: string | null, duration?: number,
|
|
516
|
+
): ExtractedContent {
|
|
517
|
+
if (frames.length === 0) {
|
|
518
|
+
const msg = error ?? "Frame extraction failed";
|
|
519
|
+
return { url, title: `Frames ${label} (0/${requestedCount})`, content: msg, error: msg };
|
|
520
|
+
}
|
|
521
|
+
return {
|
|
522
|
+
url,
|
|
523
|
+
title: `Frames ${label} (${frames.length}/${requestedCount})`,
|
|
524
|
+
content: `${frames.length} frames extracted from ${label}`,
|
|
525
|
+
error: null,
|
|
526
|
+
frames,
|
|
527
|
+
...(duration !== undefined ? { duration } : {}),
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
async function extractLocalFrames(
|
|
532
|
+
filePath: string, timestamps: number[],
|
|
533
|
+
): Promise<{ frames: VideoFrame[]; error: string | null }> {
|
|
534
|
+
const results = await Promise.all(timestamps.map(async (t) => {
|
|
535
|
+
const frame = await extractVideoFrame(filePath, t);
|
|
536
|
+
if ("error" in frame) return { error: frame.error };
|
|
537
|
+
return { ...frame, timestamp: formatSeconds(t) };
|
|
538
|
+
}));
|
|
539
|
+
const frames = results.filter((f): f is VideoFrame => "data" in f);
|
|
540
|
+
const firstError = results.find((f): f is { error: string } => "error" in f);
|
|
541
|
+
return { frames, error: frames.length === 0 && firstError ? firstError.error : null };
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
type LocalVideoInfoResult =
|
|
545
|
+
| { status: "video"; info: NonNullable<ReturnType<typeof isVideoFile>> }
|
|
546
|
+
| { status: "not-video" }
|
|
547
|
+
| { status: "invalid"; error: string };
|
|
548
|
+
|
|
549
|
+
function safeVideoInfo(url: string): LocalVideoInfoResult {
|
|
550
|
+
try {
|
|
551
|
+
const info = isVideoFile(url);
|
|
552
|
+
return info ? { status: "video", info } : { status: "not-video" };
|
|
553
|
+
} catch (err) {
|
|
554
|
+
return { status: "invalid", error: errorMessage(err) };
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
export async function extractContent(
|
|
559
|
+
url: string,
|
|
560
|
+
signal?: AbortSignal,
|
|
561
|
+
options?: ExtractOptions,
|
|
562
|
+
): Promise<ExtractedContent> {
|
|
563
|
+
if (signal?.aborted) {
|
|
564
|
+
return { url, title: "", content: "", error: "Aborted" };
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
let redirectPolicy: RedirectPolicy | undefined;
|
|
568
|
+
try {
|
|
569
|
+
redirectPolicy = options?.redirects ?? loadFetchContentRedirectPolicy();
|
|
570
|
+
} catch (err) {
|
|
571
|
+
return { url, title: "", content: "", error: errorMessage(err) };
|
|
572
|
+
}
|
|
573
|
+
let remoteUrl: URL | null = null;
|
|
574
|
+
try {
|
|
575
|
+
const parsed = new URL(url);
|
|
576
|
+
if (parsed.protocol === "http:" || parsed.protocol === "https:") remoteUrl = parsed;
|
|
577
|
+
} catch {
|
|
578
|
+
}
|
|
579
|
+
if (remoteUrl) {
|
|
580
|
+
try {
|
|
581
|
+
const ssrf = loadSsrfConfig();
|
|
582
|
+
const domainPolicy = loadFetchContentDomainPolicy();
|
|
583
|
+
// An invalid configured User-Agent or curl command fails here, before any provider fallback runs.
|
|
584
|
+
loadFetchContentUserAgent();
|
|
585
|
+
loadFetchContentCurl();
|
|
586
|
+
await validateRemoteUrl(remoteUrl, {
|
|
587
|
+
allowRanges: ssrf.allowRanges,
|
|
588
|
+
trustEnvProxy: ssrf.trustEnvProxy,
|
|
589
|
+
domainPolicy,
|
|
590
|
+
proxy: options?.proxy,
|
|
591
|
+
...(options?.lookup ? { lookup: options.lookup } : {}),
|
|
592
|
+
});
|
|
593
|
+
} catch (err) {
|
|
594
|
+
return { url, title: "", content: "", error: errorMessage(err) };
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
if (options?.authFetchProfile || options?.mode === "raw") {
|
|
599
|
+
try {
|
|
600
|
+
return await extractViaHttp(url, resolveFetchTimeoutMs(options), signal, options);
|
|
601
|
+
} catch (err) {
|
|
602
|
+
return { url, title: "", content: "", error: errorMessage(err) };
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
if (redirectPolicy) {
|
|
607
|
+
if (parseGitHubIssuePrUrl(url)) return redirectPolicyRouteRefusal(url, "GitHub issue/PR");
|
|
608
|
+
if (parseGitHubUrl(url)) return redirectPolicyRouteRefusal(url, "GitHub repository");
|
|
609
|
+
if (isYouTubeURL(url).isYouTube) return redirectPolicyRouteRefusal(url, "YouTube");
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
if (options?.frames || options?.timestamp) {
|
|
613
|
+
const disabled = imageGateError();
|
|
614
|
+
if (disabled) return { url, title: "", content: "", error: disabled };
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
if (options?.frames && !options.timestamp) {
|
|
618
|
+
const frameCount = options.frames;
|
|
619
|
+
const ytInfo = isYouTubeURL(url);
|
|
620
|
+
if (ytInfo.isYouTube && ytInfo.videoId) {
|
|
621
|
+
const streamInfo = await getYouTubeStreamInfo(ytInfo.videoId);
|
|
622
|
+
if ("error" in streamInfo) {
|
|
623
|
+
return { url, title: "Frames", content: streamInfo.error, error: streamInfo.error };
|
|
624
|
+
}
|
|
625
|
+
if (streamInfo.duration === null) {
|
|
626
|
+
const error = "Cannot determine video duration. Use a timestamp range instead.";
|
|
627
|
+
return { url, title: "Frames", content: error, error };
|
|
628
|
+
}
|
|
629
|
+
const dur = Math.floor(streamInfo.duration);
|
|
630
|
+
const timestamps = computeRangeTimestamps(0, dur, frameCount);
|
|
631
|
+
const result = await extractYouTubeFrames(ytInfo.videoId, timestamps, streamInfo);
|
|
632
|
+
const label = `${formatSeconds(0)}-${formatSeconds(dur)}`;
|
|
633
|
+
return buildFrameResult(url, label, timestamps.length, result.frames, result.error, streamInfo.duration);
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
const localVideo = safeVideoInfo(url);
|
|
637
|
+
if (localVideo.status === "invalid") {
|
|
638
|
+
return { url, title: "", content: "", error: localVideo.error };
|
|
639
|
+
}
|
|
640
|
+
if (localVideo.status === "video") {
|
|
641
|
+
const durationResult = await getLocalVideoDuration(localVideo.info.absolutePath);
|
|
642
|
+
if (typeof durationResult !== "number") {
|
|
643
|
+
return { url, title: "Frames", content: durationResult.error, error: durationResult.error };
|
|
644
|
+
}
|
|
645
|
+
const dur = Math.floor(durationResult);
|
|
646
|
+
const timestamps = computeRangeTimestamps(0, dur, frameCount);
|
|
647
|
+
const result = await extractLocalFrames(localVideo.info.absolutePath, timestamps);
|
|
648
|
+
const label = `${formatSeconds(0)}-${formatSeconds(dur)}`;
|
|
649
|
+
return buildFrameResult(url, label, timestamps.length, result.frames, result.error, durationResult);
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
return { url, title: "", content: "", error: "Frame extraction only works with YouTube and local video files" };
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
if (options?.timestamp) {
|
|
656
|
+
const spec = parseTimestampSpec(options.timestamp);
|
|
657
|
+
if (!spec) {
|
|
658
|
+
return {
|
|
659
|
+
url,
|
|
660
|
+
title: "",
|
|
661
|
+
content: "",
|
|
662
|
+
error: `Invalid timestamp format: "${options.timestamp}". Use "H:MM:SS", "MM:SS", "85", or "start-end".`,
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
const frameCount = options.frames;
|
|
667
|
+
const ytInfo = isYouTubeURL(url);
|
|
668
|
+
if (ytInfo.isYouTube && ytInfo.videoId) {
|
|
669
|
+
const streamInfo = await getYouTubeStreamInfo(ytInfo.videoId);
|
|
670
|
+
if ("error" in streamInfo) {
|
|
671
|
+
if (spec.type === "range") {
|
|
672
|
+
const label = `${formatSeconds(spec.start)}-${formatSeconds(spec.end)}`;
|
|
673
|
+
return { url, title: `Frames ${label}`, content: streamInfo.error, error: streamInfo.error };
|
|
674
|
+
}
|
|
675
|
+
if (frameCount) {
|
|
676
|
+
const end = spec.seconds + (frameCount - 1) * MIN_FRAME_INTERVAL;
|
|
677
|
+
const label = `${formatSeconds(spec.seconds)}-${formatSeconds(end)}`;
|
|
678
|
+
return { url, title: `Frames ${label}`, content: streamInfo.error, error: streamInfo.error };
|
|
679
|
+
}
|
|
680
|
+
return { url, title: `Frame at ${options.timestamp}`, content: streamInfo.error, error: streamInfo.error };
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
if (spec.type === "range") {
|
|
684
|
+
const label = `${formatSeconds(spec.start)}-${formatSeconds(spec.end)}`;
|
|
685
|
+
if (streamInfo.duration !== null && spec.end > streamInfo.duration) {
|
|
686
|
+
const error = `Timestamp ${formatSeconds(spec.end)} exceeds video duration (${formatSeconds(Math.floor(streamInfo.duration))})`;
|
|
687
|
+
return { url, title: `Frames ${label}`, content: error, error };
|
|
688
|
+
}
|
|
689
|
+
const timestamps = frameCount
|
|
690
|
+
? computeRangeTimestamps(spec.start, spec.end, frameCount)
|
|
691
|
+
: computeRangeTimestamps(spec.start, spec.end);
|
|
692
|
+
const result = await extractYouTubeFrames(ytInfo.videoId, timestamps, streamInfo);
|
|
693
|
+
return buildFrameResult(url, label, timestamps.length, result.frames, result.error, result.duration ?? undefined);
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
if (frameCount) {
|
|
697
|
+
const end = spec.seconds + (frameCount - 1) * MIN_FRAME_INTERVAL;
|
|
698
|
+
const label = `${formatSeconds(spec.seconds)}-${formatSeconds(end)}`;
|
|
699
|
+
if (streamInfo.duration !== null && end > streamInfo.duration) {
|
|
700
|
+
const error = `Timestamp ${formatSeconds(end)} exceeds video duration (${formatSeconds(Math.floor(streamInfo.duration))})`;
|
|
701
|
+
return { url, title: `Frames ${label}`, content: error, error };
|
|
702
|
+
}
|
|
703
|
+
const timestamps = computeRangeTimestamps(spec.seconds, end, frameCount);
|
|
704
|
+
const result = await extractYouTubeFrames(ytInfo.videoId, timestamps, streamInfo);
|
|
705
|
+
return buildFrameResult(url, label, timestamps.length, result.frames, result.error, result.duration ?? undefined);
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
if (streamInfo.duration !== null && spec.seconds > streamInfo.duration) {
|
|
709
|
+
const error = `Timestamp ${formatSeconds(spec.seconds)} exceeds video duration (${formatSeconds(Math.floor(streamInfo.duration))})`;
|
|
710
|
+
return { url, title: `Frame at ${options.timestamp}`, content: error, error };
|
|
711
|
+
}
|
|
712
|
+
const frame = await extractYouTubeFrame(ytInfo.videoId, spec.seconds, streamInfo);
|
|
713
|
+
if ("error" in frame) {
|
|
714
|
+
return { url, title: `Frame at ${options.timestamp}`, content: frame.error, error: frame.error };
|
|
715
|
+
}
|
|
716
|
+
// mimeType marks the image as the payload (like direct-image fetches); a
|
|
717
|
+
// text result with a bonus thumbnail stays without one.
|
|
718
|
+
return { url, title: `Frame at ${options.timestamp}`, content: `Video frame at ${options.timestamp}`, error: null, thumbnail: frame, mimeType: frame.mimeType };
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
const localVideo = safeVideoInfo(url);
|
|
722
|
+
if (localVideo.status === "invalid") {
|
|
723
|
+
return { url, title: "", content: "", error: localVideo.error };
|
|
724
|
+
}
|
|
725
|
+
if (localVideo.status === "video") {
|
|
726
|
+
if (spec.type === "range") {
|
|
727
|
+
const timestamps = frameCount
|
|
728
|
+
? computeRangeTimestamps(spec.start, spec.end, frameCount)
|
|
729
|
+
: computeRangeTimestamps(spec.start, spec.end);
|
|
730
|
+
const result = await extractLocalFrames(localVideo.info.absolutePath, timestamps);
|
|
731
|
+
const label = `${formatSeconds(spec.start)}-${formatSeconds(spec.end)}`;
|
|
732
|
+
return buildFrameResult(url, label, timestamps.length, result.frames, result.error);
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
if (frameCount) {
|
|
736
|
+
const end = spec.seconds + (frameCount - 1) * MIN_FRAME_INTERVAL;
|
|
737
|
+
const timestamps = computeRangeTimestamps(spec.seconds, end, frameCount);
|
|
738
|
+
const result = await extractLocalFrames(localVideo.info.absolutePath, timestamps);
|
|
739
|
+
const label = `${formatSeconds(spec.seconds)}-${formatSeconds(end)}`;
|
|
740
|
+
return buildFrameResult(url, label, timestamps.length, result.frames, result.error);
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
const frame = await extractVideoFrame(localVideo.info.absolutePath, spec.seconds);
|
|
744
|
+
if ("error" in frame) {
|
|
745
|
+
return { url, title: `Frame at ${options.timestamp}`, content: frame.error, error: frame.error };
|
|
746
|
+
}
|
|
747
|
+
return { url, title: `Frame at ${options.timestamp}`, content: `Video frame at ${options.timestamp}`, error: null, thumbnail: frame, mimeType: frame.mimeType };
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
return { url, title: "", content: "", error: "Timestamp extraction only works with YouTube and local video files" };
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
const localVideo = safeVideoInfo(url);
|
|
754
|
+
if (localVideo.status === "invalid") {
|
|
755
|
+
return { url, title: "", content: "", error: localVideo.error };
|
|
756
|
+
}
|
|
757
|
+
if (localVideo.status === "video") {
|
|
758
|
+
try {
|
|
759
|
+
const result = await extractVideo(localVideo.info, signal, options);
|
|
760
|
+
if (signal?.aborted) return abortedResult(url);
|
|
761
|
+
return result ?? { url, title: "", content: "", error: `Video analysis requires Gemini access. Either:\n 1. Set GEMINI_API_KEY in ${WEB_SEARCH_CONFIG_PATH}\n 2. ${browserCookieAccessHint(options?.browserCookieConsent, " ")}` };
|
|
762
|
+
} catch (err) {
|
|
763
|
+
if (isAbortError(err)) return abortedResult(url);
|
|
764
|
+
return { url, title: "", content: "", error: errorMessage(err) };
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
try {
|
|
769
|
+
if (!remoteUrl) new URL(url);
|
|
770
|
+
} catch (err) {
|
|
771
|
+
return { url, title: "", content: "", error: errorMessage(err) };
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
try {
|
|
775
|
+
const ghIssuePrResult = await extractGitHubIssuePr(url, signal, options);
|
|
776
|
+
if (ghIssuePrResult) return ghIssuePrResult;
|
|
777
|
+
if (signal?.aborted) return abortedResult(url);
|
|
778
|
+
} catch (err) {
|
|
779
|
+
const message = errorMessage(err);
|
|
780
|
+
if (isAbortError(err)) return abortedResult(url);
|
|
781
|
+
if (isConfigParseError(err)) {
|
|
782
|
+
return { url, title: "", content: "", error: message };
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
try {
|
|
787
|
+
const ghResult = await extractGitHub(url, signal, options?.forceClone);
|
|
788
|
+
if (ghResult) return ghResult;
|
|
789
|
+
if (signal?.aborted) return abortedResult(url);
|
|
790
|
+
} catch (err) {
|
|
791
|
+
const message = errorMessage(err);
|
|
792
|
+
if (isAbortError(err)) return abortedResult(url);
|
|
793
|
+
if (isConfigParseError(err)) {
|
|
794
|
+
return { url, title: "", content: "", error: message };
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
const ytInfo = isYouTubeURL(url);
|
|
799
|
+
let youtubeEnabled = false;
|
|
800
|
+
try {
|
|
801
|
+
youtubeEnabled = isYouTubeEnabled();
|
|
802
|
+
} catch (err) {
|
|
803
|
+
return { url, title: "", content: "", error: errorMessage(err) };
|
|
804
|
+
}
|
|
805
|
+
if (ytInfo.isYouTube && youtubeEnabled) {
|
|
806
|
+
try {
|
|
807
|
+
const ytResult = await extractYouTube(url, signal, options?.prompt, options?.model, options?.browserCookieConsent);
|
|
808
|
+
if (ytResult) return ytResult;
|
|
809
|
+
if (signal?.aborted) return abortedResult(url);
|
|
810
|
+
} catch (err) {
|
|
811
|
+
const message = errorMessage(err);
|
|
812
|
+
if (isAbortError(err)) return abortedResult(url);
|
|
813
|
+
return { url, title: "", content: "", error: message };
|
|
814
|
+
}
|
|
815
|
+
return {
|
|
816
|
+
url,
|
|
817
|
+
title: "",
|
|
818
|
+
content: "",
|
|
819
|
+
error: youTubeAccessError(options?.browserCookieConsent),
|
|
820
|
+
};
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
if (signal?.aborted) return abortedResult(url);
|
|
824
|
+
|
|
825
|
+
let fetchTimeoutMs: number;
|
|
826
|
+
try {
|
|
827
|
+
fetchTimeoutMs = resolveFetchTimeoutMs(options);
|
|
828
|
+
} catch (err) {
|
|
829
|
+
return { url, title: "", content: "", error: errorMessage(err) };
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
let fetchRouting: FetchRouting;
|
|
833
|
+
try {
|
|
834
|
+
fetchRouting = loadFetchRouting();
|
|
835
|
+
if (getRetrievalOnlyPolicy().enabled) {
|
|
836
|
+
// Model providers leave the order even when listed or forced; a list of only those chose the source and is refused.
|
|
837
|
+
const providers = fetchRouting.providers.filter(provider => FETCH_PROVIDER_KINDS[provider] !== "model");
|
|
838
|
+
if (providers.length === 0) throw retrievalOnlyExhaustedError("fetch provider", fetchRouting.providers);
|
|
839
|
+
fetchRouting = { ...fetchRouting, providers };
|
|
840
|
+
}
|
|
841
|
+
} catch (err) {
|
|
842
|
+
return { url, title: "", content: "", error: errorMessage(err) };
|
|
843
|
+
}
|
|
844
|
+
if (redirectPolicy && !fetchRouting.providers.includes("http")) {
|
|
845
|
+
return redirectPolicyRouteRefusal(url, fetchRouting.providers[0]!);
|
|
846
|
+
}
|
|
847
|
+
const providerOrder: FetchProvider[] = redirectPolicy
|
|
848
|
+
? ["http"]
|
|
849
|
+
: remoteUrl && !fetchRouting.allowRemoteHostedProviders
|
|
850
|
+
? fetchRouting.providers.filter(provider => !REMOTE_HOSTED_FETCH_PROVIDERS.has(provider))
|
|
851
|
+
: fetchRouting.providers;
|
|
852
|
+
if (providerOrder.length === 0) {
|
|
853
|
+
return {
|
|
854
|
+
url,
|
|
855
|
+
title: "",
|
|
856
|
+
content: "",
|
|
857
|
+
error: "Remote hosted fetch providers are disabled unless fetchRouting.allowRemoteHostedProviders is true",
|
|
858
|
+
};
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
let httpResult: ExtractedContent | null = null;
|
|
862
|
+
let declaredLinks: DeclaredWebLink[] = [];
|
|
863
|
+
const withDeclaredLinks = (result: ExtractedContent): ExtractedContent => ({
|
|
864
|
+
...result,
|
|
865
|
+
content: appendDeclaredWebLinks(result.content, declaredLinks),
|
|
866
|
+
});
|
|
867
|
+
const parseErrorResult = (message: string): ExtractedContent => httpResult
|
|
868
|
+
? { ...httpResult, error: message }
|
|
869
|
+
: { url, title: "", content: "", error: message };
|
|
870
|
+
const runHttpProvider = async (): Promise<ExtractedContent | null> => {
|
|
871
|
+
const { declaredLinks: discoveredLinks = [], ...result } = await extractViaHttp(url, fetchTimeoutMs, signal, options);
|
|
872
|
+
httpResult = result;
|
|
873
|
+
declaredLinks = discoveredLinks;
|
|
874
|
+
if (signal?.aborted) return abortedResult(url);
|
|
875
|
+
if (!httpResult.error) return httpResult;
|
|
876
|
+
if (isNonRecoverableHttpError(httpResult.error) || httpResult.error === options?.rejectDirectImages) {
|
|
877
|
+
return httpResult;
|
|
878
|
+
}
|
|
879
|
+
return null;
|
|
880
|
+
};
|
|
881
|
+
|
|
882
|
+
let firecrawlError: string | null = null;
|
|
883
|
+
let crawl4aiError: string | null = null;
|
|
884
|
+
let tinyfishError: string | null = null;
|
|
885
|
+
let queritError: string | null = null;
|
|
886
|
+
let tabstackError: string | null = null;
|
|
887
|
+
let kagiError: string | null = null;
|
|
888
|
+
let ollamaError: string | null = null;
|
|
889
|
+
let parallelError: string | null = null;
|
|
890
|
+
let parallelMcpError: string | null = null;
|
|
891
|
+
let brightdataError: string | null = null;
|
|
892
|
+
let deepseekError: string | null = null;
|
|
893
|
+
let exaError: string | null = null;
|
|
894
|
+
|
|
895
|
+
if (remoteUrl && providerOrder[0] !== "http") {
|
|
896
|
+
const httpGateResult = await runHttpProvider();
|
|
897
|
+
if (httpGateResult) return httpGateResult;
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
for (const provider of providerOrder) {
|
|
901
|
+
if (signal?.aborted) return abortedResult(url);
|
|
902
|
+
|
|
903
|
+
if (provider === "http") {
|
|
904
|
+
const result = await runHttpProvider();
|
|
905
|
+
if (result) return result;
|
|
906
|
+
continue;
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
if (provider === "firecrawl") {
|
|
910
|
+
try {
|
|
911
|
+
if (isFirecrawlAvailable()) {
|
|
912
|
+
const ssrf = loadSsrfConfig();
|
|
913
|
+
const firecrawlResult = await extractWithFirecrawl(url, signal, {
|
|
914
|
+
timeoutMs: options?.timeoutMs,
|
|
915
|
+
...(options?.lookup ? { lookup: options.lookup } : {}),
|
|
916
|
+
ssrf,
|
|
917
|
+
});
|
|
918
|
+
if (firecrawlResult) return withDeclaredLinks(firecrawlResult);
|
|
919
|
+
}
|
|
920
|
+
} catch (err) {
|
|
921
|
+
if (isAbortError(err)) return abortedResult(url);
|
|
922
|
+
firecrawlError = errorMessage(err);
|
|
923
|
+
if (isConfigParseError(err)) return parseErrorResult(firecrawlError);
|
|
924
|
+
}
|
|
925
|
+
continue;
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
if (provider === "crawl4ai") {
|
|
929
|
+
try {
|
|
930
|
+
if (isCrawl4aiAvailable()) {
|
|
931
|
+
const ssrf = loadSsrfConfig();
|
|
932
|
+
const crawl4aiResult = await extractWithCrawl4ai(url, signal, {
|
|
933
|
+
timeoutMs: options?.timeoutMs,
|
|
934
|
+
...(options?.lookup ? { lookup: options.lookup } : {}),
|
|
935
|
+
ssrf,
|
|
936
|
+
});
|
|
937
|
+
if (crawl4aiResult) return withDeclaredLinks(crawl4aiResult);
|
|
938
|
+
}
|
|
939
|
+
} catch (err) {
|
|
940
|
+
if (signal?.aborted || isAbortException(err)) return abortedResult(url);
|
|
941
|
+
crawl4aiError = errorMessage(err);
|
|
942
|
+
if (isConfigParseError(err)) return parseErrorResult(crawl4aiError);
|
|
943
|
+
}
|
|
944
|
+
continue;
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
if (provider === "jina") {
|
|
948
|
+
const jinaResult = await extractWithJinaReader(url, fetchTimeoutMs, signal, options?.lookup);
|
|
949
|
+
if (jinaResult) return withDeclaredLinks(jinaResult);
|
|
950
|
+
continue;
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
if (provider === "tinyfish") {
|
|
954
|
+
try {
|
|
955
|
+
if (isTinyFishAvailable()) {
|
|
956
|
+
const tinyfishResult = await extractWithTinyFish(url, signal, options);
|
|
957
|
+
if (tinyfishResult) return withDeclaredLinks(tinyfishResult);
|
|
958
|
+
}
|
|
959
|
+
} catch (err) {
|
|
960
|
+
if (isAbortError(err)) return abortedResult(url);
|
|
961
|
+
tinyfishError = errorMessage(err);
|
|
962
|
+
if (isConfigParseError(err)) return parseErrorResult(tinyfishError);
|
|
963
|
+
}
|
|
964
|
+
continue;
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
if (provider === "querit") {
|
|
968
|
+
try {
|
|
969
|
+
if (isQueritAvailable()) {
|
|
970
|
+
const queritResult = await extractWithQuerit(url, signal, options);
|
|
971
|
+
if (queritResult) return withDeclaredLinks(queritResult);
|
|
972
|
+
}
|
|
973
|
+
} catch (err) {
|
|
974
|
+
if (isAbortError(err)) return abortedResult(url);
|
|
975
|
+
queritError = errorMessage(err);
|
|
976
|
+
if (isConfigParseError(err)) return parseErrorResult(queritError);
|
|
977
|
+
}
|
|
978
|
+
continue;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
if (provider === "tabstack") {
|
|
982
|
+
try {
|
|
983
|
+
if (isTabstackAvailable()) {
|
|
984
|
+
const tabstackResult = await extractWithTabstack(url, signal, options);
|
|
985
|
+
if (tabstackResult) return withDeclaredLinks(tabstackResult);
|
|
986
|
+
}
|
|
987
|
+
} catch (err) {
|
|
988
|
+
if (isAbortError(err)) return abortedResult(url);
|
|
989
|
+
tabstackError = errorMessage(err);
|
|
990
|
+
if (isConfigParseError(err)) return parseErrorResult(tabstackError);
|
|
991
|
+
}
|
|
992
|
+
continue;
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
if (provider === "kagi") {
|
|
996
|
+
try {
|
|
997
|
+
if (isKagiExtractAvailable()) {
|
|
998
|
+
const ssrf = loadSsrfConfig();
|
|
999
|
+
const kagiResult = await extractWithKagi(url, signal, {
|
|
1000
|
+
timeoutMs: options?.timeoutMs,
|
|
1001
|
+
...(options?.lookup ? { lookup: options.lookup } : {}),
|
|
1002
|
+
ssrf,
|
|
1003
|
+
});
|
|
1004
|
+
if (kagiResult) return withDeclaredLinks(kagiResult);
|
|
1005
|
+
}
|
|
1006
|
+
} catch (err) {
|
|
1007
|
+
if (isAbortError(err)) return abortedResult(url);
|
|
1008
|
+
kagiError = errorMessage(err);
|
|
1009
|
+
if (isConfigParseError(err)) return parseErrorResult(kagiError);
|
|
1010
|
+
}
|
|
1011
|
+
continue;
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
if (provider === "ollama") {
|
|
1015
|
+
try {
|
|
1016
|
+
if (isOllamaFetchAvailable()) {
|
|
1017
|
+
const ssrf = loadSsrfConfig();
|
|
1018
|
+
const ollamaResult = await extractWithOllama(url, signal, {
|
|
1019
|
+
timeoutMs: options?.timeoutMs,
|
|
1020
|
+
...(options?.lookup ? { lookup: options.lookup } : {}),
|
|
1021
|
+
ssrf,
|
|
1022
|
+
});
|
|
1023
|
+
if (ollamaResult) return withDeclaredLinks(ollamaResult);
|
|
1024
|
+
}
|
|
1025
|
+
} catch (err) {
|
|
1026
|
+
if (isAbortError(err)) return abortedResult(url);
|
|
1027
|
+
ollamaError = errorMessage(err);
|
|
1028
|
+
if (isConfigParseError(err)) return parseErrorResult(ollamaError);
|
|
1029
|
+
}
|
|
1030
|
+
continue;
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
if (provider === "parallel") {
|
|
1034
|
+
try {
|
|
1035
|
+
if (isParallelAvailable()) {
|
|
1036
|
+
const parallelResult = await extractWithParallel(url, signal, options);
|
|
1037
|
+
if (parallelResult) return withDeclaredLinks(parallelResult);
|
|
1038
|
+
}
|
|
1039
|
+
} catch (err) {
|
|
1040
|
+
if (isAbortError(err)) return abortedResult(url);
|
|
1041
|
+
parallelError = errorMessage(err);
|
|
1042
|
+
if (isConfigParseError(err)) return parseErrorResult(parallelError);
|
|
1043
|
+
}
|
|
1044
|
+
continue;
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
if (provider === "parallel-mcp") {
|
|
1048
|
+
try {
|
|
1049
|
+
const parallelMcpResult = await extractWithParallelMcp(url, signal, options);
|
|
1050
|
+
if (parallelMcpResult) return withDeclaredLinks(parallelMcpResult);
|
|
1051
|
+
} catch (err) {
|
|
1052
|
+
if (isAbortError(err)) return abortedResult(url);
|
|
1053
|
+
parallelMcpError = errorMessage(err);
|
|
1054
|
+
if (isConfigParseError(err)) return parseErrorResult(parallelMcpError);
|
|
1055
|
+
}
|
|
1056
|
+
continue;
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
if (provider === "brightdata") {
|
|
1060
|
+
try {
|
|
1061
|
+
if (isBrightDataUnlockerAvailable()) {
|
|
1062
|
+
const ssrf = loadSsrfConfig();
|
|
1063
|
+
const brightdataResult = await extractWithBrightDataUnlocker(url, signal, {
|
|
1064
|
+
timeoutMs: options?.timeoutMs,
|
|
1065
|
+
...(options?.lookup ? { lookup: options.lookup } : {}),
|
|
1066
|
+
ssrf,
|
|
1067
|
+
});
|
|
1068
|
+
if (brightdataResult) return withDeclaredLinks(brightdataResult);
|
|
1069
|
+
}
|
|
1070
|
+
} catch (err) {
|
|
1071
|
+
if (isAbortError(err)) return abortedResult(url);
|
|
1072
|
+
brightdataError = errorMessage(err);
|
|
1073
|
+
if (isConfigParseError(err)) return parseErrorResult(brightdataError);
|
|
1074
|
+
}
|
|
1075
|
+
continue;
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
if (provider === "gemini") {
|
|
1079
|
+
let geminiResult: ExtractedContent | null = null;
|
|
1080
|
+
try {
|
|
1081
|
+
geminiResult = await extractWithUrlContext(url, signal)
|
|
1082
|
+
?? await extractWithGeminiWeb(url, signal);
|
|
1083
|
+
} catch (err) {
|
|
1084
|
+
if (isAbortError(err)) return abortedResult(url);
|
|
1085
|
+
if (err instanceof CredentialResolutionError || isConfigParseError(err)) {
|
|
1086
|
+
return parseErrorResult(errorMessage(err));
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
if (geminiResult) return withDeclaredLinks(geminiResult);
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
if (provider === "deepseek") {
|
|
1093
|
+
try {
|
|
1094
|
+
if (isDeepSeekAvailable()) {
|
|
1095
|
+
const deepseekResult = await extractWithDeepSeek(url, signal, {
|
|
1096
|
+
timeoutMs: options?.timeoutMs,
|
|
1097
|
+
...(options?.lookup ? { lookup: options.lookup } : {}),
|
|
1098
|
+
});
|
|
1099
|
+
if (deepseekResult) return withDeclaredLinks(deepseekResult);
|
|
1100
|
+
}
|
|
1101
|
+
} catch (err) {
|
|
1102
|
+
if (isAbortError(err)) return abortedResult(url);
|
|
1103
|
+
deepseekError = errorMessage(err);
|
|
1104
|
+
if (isConfigParseError(err)) return parseErrorResult(deepseekError);
|
|
1105
|
+
}
|
|
1106
|
+
continue;
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
if (provider === "exa") {
|
|
1110
|
+
try {
|
|
1111
|
+
if (hasExaApiKey()) {
|
|
1112
|
+
const exaResult = await extractWithExa(url, signal, {
|
|
1113
|
+
timeoutMs: options?.timeoutMs,
|
|
1114
|
+
...(options?.lookup ? { lookup: options.lookup } : {}),
|
|
1115
|
+
});
|
|
1116
|
+
if (exaResult) return withDeclaredLinks(exaResult);
|
|
1117
|
+
}
|
|
1118
|
+
} catch (err) {
|
|
1119
|
+
if (isAbortError(err)) return abortedResult(url);
|
|
1120
|
+
exaError = errorMessage(err);
|
|
1121
|
+
if (isConfigParseError(err)) return parseErrorResult(exaError);
|
|
1122
|
+
}
|
|
1123
|
+
continue;
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
if (signal?.aborted) return abortedResult(url);
|
|
1128
|
+
const finalHttpResult = httpResult as ExtractedContent | null;
|
|
1129
|
+
if (finalHttpResult && declaredLinks.length > 0) return { ...finalHttpResult, error: null };
|
|
1130
|
+
|
|
1131
|
+
// A definitive 404/410 from the origin means no extraction provider can
|
|
1132
|
+
// retrieve the page, so the provider-configuration checklist below would
|
|
1133
|
+
// send users down the wrong path. Point at search instead.
|
|
1134
|
+
if (finalHttpResult?.status === 404 || finalHttpResult?.status === 410) {
|
|
1135
|
+
return { ...finalHttpResult, error: notFoundGuidance(finalHttpResult, options?.toolNames) };
|
|
1136
|
+
}
|
|
1137
|
+
// Under the redirect policy no other provider may run, so provider setup hints do not apply.
|
|
1138
|
+
if (redirectPolicy && finalHttpResult) return finalHttpResult;
|
|
1139
|
+
|
|
1140
|
+
const searchToolName = options?.toolNames?.webSearch;
|
|
1141
|
+
const jinaHint = jinaReaderGuidance(fetchRouting, providerOrder, Boolean(remoteUrl) && !fetchRouting.allowRemoteHostedProviders);
|
|
1142
|
+
const guidance = [
|
|
1143
|
+
finalHttpResult?.error ?? "No fetch_content provider returned content",
|
|
1144
|
+
...(firecrawlError ? [`Firecrawl fallback failed: ${firecrawlError}`] : []),
|
|
1145
|
+
...(crawl4aiError ? [`Crawl4AI fallback failed: ${crawl4aiError}`] : []),
|
|
1146
|
+
...(tinyfishError ? [`TinyFish fallback failed: ${tinyfishError}`] : []),
|
|
1147
|
+
...(queritError ? [`Querit fallback failed: ${queritError}`] : []),
|
|
1148
|
+
...(kagiError ? [`Kagi fallback failed: ${kagiError}`] : []),
|
|
1149
|
+
...(ollamaError ? [`Ollama fallback failed: ${ollamaError}`] : []),
|
|
1150
|
+
...(parallelError ? [`Parallel fallback failed: ${parallelError}`] : []),
|
|
1151
|
+
...(parallelMcpError ? [`Parallel MCP fallback failed: ${parallelMcpError}`] : []),
|
|
1152
|
+
...(brightdataError ? [`Bright Data fallback failed: ${brightdataError}`] : []),
|
|
1153
|
+
...(deepseekError ? [`DeepSeek fallback failed: ${deepseekError}`] : []),
|
|
1154
|
+
...(exaError ? [`Exa fallback failed: ${exaError}`] : []),
|
|
1155
|
+
...(tabstackError ? [`Tabstack fallback failed: ${tabstackError}`] : []),
|
|
1156
|
+
"",
|
|
1157
|
+
"Fallback options:",
|
|
1158
|
+
...(jinaHint ? [jinaHint] : []),
|
|
1159
|
+
` • Set firecrawlBaseUrl in ${WEB_SEARCH_CONFIG_PATH} to a self-hosted Firecrawl instance`,
|
|
1160
|
+
` • Set crawl4aiBaseUrl in ${WEB_SEARCH_CONFIG_PATH} to a self-hosted Crawl4AI instance`,
|
|
1161
|
+
` • Set tinyfishApiKey in ${WEB_SEARCH_CONFIG_PATH} or TINYFISH_API_KEY`,
|
|
1162
|
+
` • Set queritApiKey in ${WEB_SEARCH_CONFIG_PATH} or QUERIT_API_KEY`,
|
|
1163
|
+
` • Set kagiApiKey in ${WEB_SEARCH_CONFIG_PATH} or KAGI_API_KEY`,
|
|
1164
|
+
` • Set ollamaApiKey in ${WEB_SEARCH_CONFIG_PATH} or OLLAMA_API_KEY`,
|
|
1165
|
+
` • Set parallelApiKey in ${WEB_SEARCH_CONFIG_PATH} or PARALLEL_API_KEY`,
|
|
1166
|
+
` • Set brightdataApiKey and brightdataUnlockerZone in ${WEB_SEARCH_CONFIG_PATH} or BRIGHTDATA_API_KEY and BRIGHTDATA_UNLOCKER_ZONE`,
|
|
1167
|
+
` • Set deepseekApiKey in ${WEB_SEARCH_CONFIG_PATH} or DEEPSEEK_API_KEY and add "deepseek" to fetchRouting.providers`,
|
|
1168
|
+
` • Set exaApiKey in ${WEB_SEARCH_CONFIG_PATH} or EXA_API_KEY and add "exa" to fetchRouting.providers`,
|
|
1169
|
+
` • Set tabstackApiKey in ${WEB_SEARCH_CONFIG_PATH} or TABSTACK_API_KEY and add "tabstack" to fetchRouting.providers`,
|
|
1170
|
+
// Gemini page fetching is a model route, so it is no way forward under the retrieval-only policy.
|
|
1171
|
+
...(getRetrievalOnlyPolicy().enabled ? [] : [` • Set GEMINI_API_KEY in ${WEB_SEARCH_CONFIG_PATH}`, ` • ${browserCookieAccessHintLine()}`]),
|
|
1172
|
+
...(searchToolName ? [` • Use ${searchToolName} to find content about this topic`] : []),
|
|
1173
|
+
].join("\n");
|
|
1174
|
+
return { ...(finalHttpResult ?? { url, title: "", content: "", error: null }), error: guidance };
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
// Cloudflare interstitials served with HTTP 200. The header is authoritative for
|
|
1178
|
+
// any text response; the body check is HTML-only and needs both challenge-platform
|
|
1179
|
+
// markers so a generic "Just a moment..." page never matches.
|
|
1180
|
+
function isCloudflareChallenge(response: Response, text: string, isHTML: boolean): boolean {
|
|
1181
|
+
if (response.status !== 200) return false;
|
|
1182
|
+
if (response.headers.get("cf-mitigated") === "challenge") return true;
|
|
1183
|
+
return isHTML &&
|
|
1184
|
+
/<title>\s*Just a moment\.\.\.\s*<\/title>/i.test(text) &&
|
|
1185
|
+
text.includes("window._cf_chl_opt") &&
|
|
1186
|
+
text.includes("/cdn-cgi/challenge-platform/");
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
// The HTML spec's JavaScript MIME type essences; any other type (JSON-LD,
|
|
1190
|
+
// text/template, ...) is a data block that never runs.
|
|
1191
|
+
const JAVASCRIPT_MIME_TYPES = new Set([
|
|
1192
|
+
"application/ecmascript", "application/javascript", "application/x-ecmascript", "application/x-javascript",
|
|
1193
|
+
"text/ecmascript", "text/javascript", "text/javascript1.0", "text/javascript1.1", "text/javascript1.2",
|
|
1194
|
+
"text/javascript1.3", "text/javascript1.4", "text/javascript1.5", "text/jscript", "text/livescript",
|
|
1195
|
+
"text/x-ecmascript", "text/x-javascript",
|
|
1196
|
+
]);
|
|
1197
|
+
|
|
1198
|
+
function isExecutableScriptType(type: string | null): boolean {
|
|
1199
|
+
const mime = (type ?? "").split(";")[0].trim().toLowerCase();
|
|
1200
|
+
return mime === "" || mime === "module" || JAVASCRIPT_MIME_TYPES.has(mime);
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
/** Removes non-rendered nodes, so pass a fresh parse. */
|
|
1204
|
+
function visibleTextLength(document: Document): number {
|
|
1205
|
+
for (const node of document.querySelectorAll("script, style, noscript, template")) node.remove();
|
|
1206
|
+
return (document.body?.textContent ?? "").replace(/\s+/g, " ").trim().length;
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
/** Markdown length as text, without images and link targets, which would
|
|
1210
|
+
* otherwise count long URLs as content. Each pattern always matches once
|
|
1211
|
+
* started, which keeps the scan linear on unbalanced brackets. */
|
|
1212
|
+
function markdownTextLength(markdown: string): number {
|
|
1213
|
+
return markdown
|
|
1214
|
+
.replace(/\]\([^)\s]*\)?/g, "]")
|
|
1215
|
+
.replace(/!\[[^\]]*\]?/g, "")
|
|
1216
|
+
.replace(/\s+/g, " ")
|
|
1217
|
+
.trim()
|
|
1218
|
+
.length;
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
function isLikelyJSRendered(html: string): boolean {
|
|
1222
|
+
const bodyMatch = html.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
|
|
1223
|
+
if (!bodyMatch) return false;
|
|
1224
|
+
|
|
1225
|
+
const bodyHtml = bodyMatch[1];
|
|
1226
|
+
|
|
1227
|
+
const textContent = bodyHtml
|
|
1228
|
+
.replace(/<script[\s\S]*?<\/script>/gi, "")
|
|
1229
|
+
.replace(/<style[\s\S]*?<\/style>/gi, "")
|
|
1230
|
+
.replace(/<[^>]+>/g, "")
|
|
1231
|
+
.replace(/\s+/g, " ")
|
|
1232
|
+
.trim();
|
|
1233
|
+
|
|
1234
|
+
const scriptCount = [...html.matchAll(/<script\b([^>]*)>/gi)]
|
|
1235
|
+
.filter(([, attrs]) => isExecutableScriptType(attrs.match(/\btype\s*=\s*["']?([^"'\s>]+)/i)?.[1] ?? null))
|
|
1236
|
+
.length;
|
|
1237
|
+
|
|
1238
|
+
return textContent.length < 500 && scriptCount > 3;
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
export async function readPDFResponseBuffer(response: Response, maxSizeMB: number): Promise<ArrayBuffer> {
|
|
1242
|
+
const maxBytes = maxSizeMB * 1024 * 1024;
|
|
1243
|
+
return readResponseBufferWithLimit(response, maxBytes, () => pdfSizeLimitError(maxSizeMB));
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
async function readTextResponseWithLimit(response: Response, maxBytes: number): Promise<string> {
|
|
1247
|
+
const buffer = await readResponseBufferWithLimit(response, maxBytes, () => responseSizeLimitError(maxBytes));
|
|
1248
|
+
const charset = response.headers.get("content-type")?.match(/charset\s*=\s*["']?([^;"'\s]+)/i)?.[1];
|
|
1249
|
+
try {
|
|
1250
|
+
return new TextDecoder(charset || "utf-8").decode(buffer);
|
|
1251
|
+
} catch {
|
|
1252
|
+
return new TextDecoder("utf-8").decode(buffer);
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
function isTextContentType(contentType: string): boolean {
|
|
1257
|
+
const mimeType = contentType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
|
|
1258
|
+
return mimeType.startsWith("text/") ||
|
|
1259
|
+
mimeType === "application/json" ||
|
|
1260
|
+
mimeType === "application/ld+json" ||
|
|
1261
|
+
mimeType === "application/xml" ||
|
|
1262
|
+
mimeType === "application/xhtml+xml" ||
|
|
1263
|
+
mimeType === "application/javascript" ||
|
|
1264
|
+
mimeType === "application/x-javascript" ||
|
|
1265
|
+
mimeType.endsWith("+json") ||
|
|
1266
|
+
mimeType.endsWith("+xml");
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
async function readResponseBufferWithLimit(
|
|
1270
|
+
response: Response,
|
|
1271
|
+
maxBytes: number,
|
|
1272
|
+
buildError: () => Error,
|
|
1273
|
+
): Promise<ArrayBuffer> {
|
|
1274
|
+
const reader = response.body?.getReader();
|
|
1275
|
+
if (!reader) {
|
|
1276
|
+
const buffer = await response.arrayBuffer();
|
|
1277
|
+
if (buffer.byteLength > maxBytes) throw buildError();
|
|
1278
|
+
return buffer;
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
const chunks: Uint8Array[] = [];
|
|
1282
|
+
let totalBytes = 0;
|
|
1283
|
+
try {
|
|
1284
|
+
while (true) {
|
|
1285
|
+
const { done, value } = await reader.read();
|
|
1286
|
+
if (done) break;
|
|
1287
|
+
if (!value) continue;
|
|
1288
|
+
totalBytes += value.byteLength;
|
|
1289
|
+
if (totalBytes > maxBytes) {
|
|
1290
|
+
await reader.cancel();
|
|
1291
|
+
throw buildError();
|
|
1292
|
+
}
|
|
1293
|
+
chunks.push(value);
|
|
1294
|
+
}
|
|
1295
|
+
} finally {
|
|
1296
|
+
reader.releaseLock();
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
const combined = new Uint8Array(totalBytes);
|
|
1300
|
+
let offset = 0;
|
|
1301
|
+
for (const chunk of chunks) {
|
|
1302
|
+
combined.set(chunk, offset);
|
|
1303
|
+
offset += chunk.byteLength;
|
|
1304
|
+
}
|
|
1305
|
+
return combined.buffer;
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
function pdfSizeLimitError(maxSizeMB: number): Error {
|
|
1309
|
+
return new Error(`PDF exceeds configured pdf.maxSizeMB limit (${maxSizeMB} MB)`);
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
function responseSizeLimitError(maxBytes: number): Error {
|
|
1313
|
+
return new Error(`Response too large (${Math.round(maxBytes / 1024 / 1024)}MB)`);
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
const BROWSER_ACCEPT = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8";
|
|
1317
|
+
// Servers that support markdown content negotiation (Cloudflare Markdown for
|
|
1318
|
+
// Agents, Mintlify, Vercel) return markdown directly; others see the same
|
|
1319
|
+
// relative preferences as BROWSER_ACCEPT. Raw mode keeps BROWSER_ACCEPT so it
|
|
1320
|
+
// returns the server's normal representation.
|
|
1321
|
+
const MARKDOWN_FIRST_ACCEPT = "text/markdown,text/html;q=0.9,application/xhtml+xml;q=0.9,application/xml;q=0.8,image/avif;q=0.9,image/webp;q=0.9,image/apng;q=0.9,*/*;q=0.7";
|
|
1322
|
+
|
|
1323
|
+
async function extractViaHttp(
|
|
1324
|
+
url: string,
|
|
1325
|
+
timeoutMs: number,
|
|
1326
|
+
signal?: AbortSignal,
|
|
1327
|
+
options?: ExtractOptions,
|
|
1328
|
+
preferMarkdown = options?.mode !== "raw",
|
|
1329
|
+
): Promise<HttpExtractedContent> {
|
|
1330
|
+
const activityId = activityMonitor.logStart({ type: "fetch", url });
|
|
1331
|
+
|
|
1332
|
+
const controller = new AbortController();
|
|
1333
|
+
const startedAt = Date.now();
|
|
1334
|
+
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
|
|
1335
|
+
|
|
1336
|
+
const onAbort = () => controller.abort();
|
|
1337
|
+
signal?.addEventListener("abort", onAbort);
|
|
1338
|
+
|
|
1339
|
+
try {
|
|
1340
|
+
const ssrf = loadSsrfConfig();
|
|
1341
|
+
const domainPolicy = loadFetchContentDomainPolicy();
|
|
1342
|
+
const redirects = options?.redirects ?? loadFetchContentRedirectPolicy();
|
|
1343
|
+
const authProfile = options?.authFetchProfile;
|
|
1344
|
+
// Auth fetches never run the configured curl command. With a proxy they still go through the
|
|
1345
|
+
// proxy's curl transport, which passes headers (the cookie too) in a private file, not argv.
|
|
1346
|
+
const curl = authProfile ? null : loadFetchContentCurl();
|
|
1347
|
+
// Through curl only a configured User-Agent is sent, so curl-impersonate keeps its browser User-Agent.
|
|
1348
|
+
const userAgent = curl ? loadConfiguredFetchContentUserAgent() : loadFetchContentUserAgent();
|
|
1349
|
+
const requestInit: ProxiedRequestInit = {
|
|
1350
|
+
signal: controller.signal,
|
|
1351
|
+
__proxy: options?.proxy,
|
|
1352
|
+
headers: {
|
|
1353
|
+
...(userAgent ? { "User-Agent": userAgent } : {}),
|
|
1354
|
+
"Accept": preferMarkdown ? MARKDOWN_FIRST_ACCEPT : BROWSER_ACCEPT,
|
|
1355
|
+
"Accept-Language": "en-US,en;q=0.9",
|
|
1356
|
+
"Cache-Control": "no-cache",
|
|
1357
|
+
"Sec-Fetch-Dest": "document",
|
|
1358
|
+
"Sec-Fetch-Mode": "navigate",
|
|
1359
|
+
"Sec-Fetch-Site": "none",
|
|
1360
|
+
"Sec-Fetch-User": "?1",
|
|
1361
|
+
"Upgrade-Insecure-Requests": "1",
|
|
1362
|
+
},
|
|
1363
|
+
};
|
|
1364
|
+
const response = authProfile
|
|
1365
|
+
? await fetchAuthenticatedRemoteUrl(url, requestInit, { ssrf, domainPolicy, redirects, proxy: options?.proxy, ...(options?.lookup ? { lookup: options.lookup } : {}) }, authProfile)
|
|
1366
|
+
: await fetchRemoteUrl(
|
|
1367
|
+
url,
|
|
1368
|
+
requestInit,
|
|
1369
|
+
{
|
|
1370
|
+
allowRanges: ssrf.allowRanges,
|
|
1371
|
+
trustEnvProxy: ssrf.trustEnvProxy,
|
|
1372
|
+
domainPolicy,
|
|
1373
|
+
redirects,
|
|
1374
|
+
proxy: options?.proxy,
|
|
1375
|
+
...(options?.lookup ? { lookup: options.lookup } : {}),
|
|
1376
|
+
...(curl ? {
|
|
1377
|
+
fetch: createCurlFetch(curl, {
|
|
1378
|
+
// The type, and so the exact limit, is known only after the response; the size checks below still apply.
|
|
1379
|
+
// curl rejects a fractional --max-filesize, and pdf.maxSizeMB may be fractional.
|
|
1380
|
+
maxBytes: Math.floor(Math.max(5, loadPDFConfig().maxSizeMB) * 1024 * 1024),
|
|
1381
|
+
envProxy: (target) => trustedEnvProxyFor(target, ssrf.trustEnvProxy),
|
|
1382
|
+
}),
|
|
1383
|
+
} : {}),
|
|
1384
|
+
},
|
|
1385
|
+
);
|
|
1386
|
+
|
|
1387
|
+
if (!response.ok && options?.mode !== "raw") {
|
|
1388
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
1389
|
+
return {
|
|
1390
|
+
url,
|
|
1391
|
+
title: "",
|
|
1392
|
+
content: "",
|
|
1393
|
+
error: `HTTP ${response.status}: ${response.statusText}`,
|
|
1394
|
+
status: response.status,
|
|
1395
|
+
};
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
const contentLengthHeader = response.headers.get("content-length");
|
|
1399
|
+
const contentType = (response.headers.get("content-type") || "").toLowerCase();
|
|
1400
|
+
const mimeType = contentType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
|
|
1401
|
+
const isPDFContent = isPDF(url, contentType);
|
|
1402
|
+
const pdfConfig = isPDFContent ? loadPDFConfig() : null;
|
|
1403
|
+
if (isPDFContent && pdfConfig && !pdfConfig.enabled) {
|
|
1404
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
1405
|
+
return { url, title: "", content: "", error: "PDF extraction is disabled by pdf.enabled", mimeType, status: response.status };
|
|
1406
|
+
}
|
|
1407
|
+
const maxResponseSize = (pdfConfig?.maxSizeMB ?? 5) * 1024 * 1024;
|
|
1408
|
+
if (contentLengthHeader) {
|
|
1409
|
+
const contentLength = Number.parseInt(contentLengthHeader, 10);
|
|
1410
|
+
if (Number.isFinite(contentLength) && contentLength > maxResponseSize) {
|
|
1411
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
1412
|
+
return {
|
|
1413
|
+
url,
|
|
1414
|
+
title: "",
|
|
1415
|
+
content: "",
|
|
1416
|
+
error: pdfConfig
|
|
1417
|
+
? pdfSizeLimitError(pdfConfig.maxSizeMB).message
|
|
1418
|
+
: `Response too large (${Math.round(contentLength / 1024 / 1024)}MB)`,
|
|
1419
|
+
};
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
if (options?.mode === "raw") {
|
|
1424
|
+
if (!isTextContentType(contentType)) {
|
|
1425
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
1426
|
+
const hint = isPDFContent ? "; retry without mode for Markdown, or with mode \"answer\" and a prompt" : "";
|
|
1427
|
+
return { url, title: "", content: "", error: `Unsupported content type in raw mode: ${mimeType || "missing"}${hint}`, mimeType, status: response.status };
|
|
1428
|
+
}
|
|
1429
|
+
const text = await readTextResponseWithLimit(response, maxResponseSize);
|
|
1430
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
1431
|
+
return { url, title: extractTextTitle(text, url), content: text, error: null, mimeType, status: response.status };
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
if (SUPPORTED_IMAGE_TYPES.has(mimeType)) {
|
|
1435
|
+
const disabled = imageGateError();
|
|
1436
|
+
if (disabled) {
|
|
1437
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
1438
|
+
return { url, title: "", content: "", error: disabled, mimeType, status: response.status };
|
|
1439
|
+
}
|
|
1440
|
+
if (options?.rejectDirectImages) {
|
|
1441
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
1442
|
+
return { url, title: "", content: "", error: options.rejectDirectImages, mimeType, status: response.status };
|
|
1443
|
+
}
|
|
1444
|
+
try {
|
|
1445
|
+
const buffer = await readResponseBufferWithLimit(response, maxResponseSize, () => responseSizeLimitError(maxResponseSize));
|
|
1446
|
+
const { resizeImage } = await import("@earendil-works/pi-coding-agent");
|
|
1447
|
+
const resized = await resizeImage(new Uint8Array(buffer), mimeType, { maxWidth: 2000, maxHeight: 2000 });
|
|
1448
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
1449
|
+
if (!resized) return { url, title: "", content: "", error: `Could not decode image: ${mimeType}`, mimeType, status: response.status };
|
|
1450
|
+
const title = new URL(response.url || url).pathname.split("/").pop() || url;
|
|
1451
|
+
return {
|
|
1452
|
+
url,
|
|
1453
|
+
title,
|
|
1454
|
+
content: `Image fetched (${resized.width}×${resized.height}, ${resized.mimeType})`,
|
|
1455
|
+
error: null,
|
|
1456
|
+
thumbnail: { data: resized.data, mimeType: resized.mimeType },
|
|
1457
|
+
mimeType: resized.mimeType,
|
|
1458
|
+
status: response.status,
|
|
1459
|
+
};
|
|
1460
|
+
} catch (err) {
|
|
1461
|
+
const message = errorMessage(err);
|
|
1462
|
+
activityMonitor.logError(activityId, message);
|
|
1463
|
+
return { url, title: "", content: "", error: message, mimeType, status: response.status };
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
if (isPDFContent && pdfConfig) {
|
|
1468
|
+
try {
|
|
1469
|
+
const buffer = await readPDFResponseBuffer(response, pdfConfig.maxSizeMB);
|
|
1470
|
+
if (signal?.aborted) return abortedResult(url);
|
|
1471
|
+
const result = await extractPDFToMarkdown(buffer, url, { signal });
|
|
1472
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
1473
|
+
return {
|
|
1474
|
+
url,
|
|
1475
|
+
title: result.title,
|
|
1476
|
+
content: options?.mode === "answer" || options?.mode === "extract"
|
|
1477
|
+
? result.content
|
|
1478
|
+
: `PDF extracted and saved to: ${result.outputPath}\n\n${result.content}`,
|
|
1479
|
+
error: null,
|
|
1480
|
+
};
|
|
1481
|
+
} catch (err) {
|
|
1482
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1483
|
+
activityMonitor.logError(activityId, message);
|
|
1484
|
+
if (message.startsWith("PDF exceeds configured pdf.maxSizeMB limit")) {
|
|
1485
|
+
return { url, title: "", content: "", error: message };
|
|
1486
|
+
}
|
|
1487
|
+
if (err instanceof CredentialResolutionError || isConfigParseError(err)) {
|
|
1488
|
+
return { url, title: "", content: "", error: message };
|
|
1489
|
+
}
|
|
1490
|
+
return { url, title: "", content: "", error: `PDF extraction failed: ${message}` };
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1494
|
+
if (contentType.includes("application/octet-stream") ||
|
|
1495
|
+
contentType.includes("image/") ||
|
|
1496
|
+
contentType.includes("audio/") ||
|
|
1497
|
+
contentType.includes("video/") ||
|
|
1498
|
+
contentType.includes("application/zip")) {
|
|
1499
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
1500
|
+
return {
|
|
1501
|
+
url,
|
|
1502
|
+
title: "",
|
|
1503
|
+
content: "",
|
|
1504
|
+
error: `Unsupported content type: ${contentType.split(";")[0]}`,
|
|
1505
|
+
};
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
const text = await readTextResponseWithLimit(response, maxResponseSize);
|
|
1509
|
+
const isHTML = contentType.includes("text/html") || contentType.includes("application/xhtml+xml");
|
|
1510
|
+
|
|
1511
|
+
if (isCloudflareChallenge(response, text, isHTML)) {
|
|
1512
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
1513
|
+
return { url, title: "", content: "", error: `HTTP ${response.status}: Blocked by Cloudflare challenge page`, status: response.status };
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1516
|
+
if (!isHTML) {
|
|
1517
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
1518
|
+
const title = extractTextTitle(text, url);
|
|
1519
|
+
if (mimeType !== "text/markdown" && mimeType !== "text/x-markdown") return { url, title, content: text, error: null };
|
|
1520
|
+
const declaredLinks = discoverDeclaredWebLinks(null, response.headers.get("link"), response.url || url);
|
|
1521
|
+
const markdown = { url, title, content: appendDeclaredWebLinks(text, declaredLinks), error: null, declaredLinks };
|
|
1522
|
+
if (!preferMarkdown || text.trim().length >= MIN_USEFUL_CONTENT) return markdown;
|
|
1523
|
+
// Short negotiated markdown is re-requested with the browser Accept header.
|
|
1524
|
+
// That response stays authoritative for policy/config rejection, not-found
|
|
1525
|
+
// status, cancellation, and any content it has. This markdown only fills a
|
|
1526
|
+
// recoverable empty response, marked incomplete with its status and error.
|
|
1527
|
+
const normal = await extractViaHttp(url, Math.max(1, timeoutMs - (Date.now() - startedAt)), signal, options, false);
|
|
1528
|
+
if (signal?.aborted || isNonRecoverableHttpError(normal.error) ||
|
|
1529
|
+
normal.status === 404 || normal.status === 410 || isAbortError(normal.error)) return normal;
|
|
1530
|
+
const normalHasBody = normal.content.trim() !== appendDeclaredWebLinks("", normal.declaredLinks ?? []).trim();
|
|
1531
|
+
if (normalHasBody || !markdown.content.trim()) return normal;
|
|
1532
|
+
return {
|
|
1533
|
+
...normal,
|
|
1534
|
+
...markdown,
|
|
1535
|
+
error: "Extracted content appears incomplete" + (normal.error ? `\nBrowser retry failed: ${normal.error}` : ""),
|
|
1536
|
+
};
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
const { parseHTML } = await import("linkedom");
|
|
1540
|
+
const { document } = parseHTML(text);
|
|
1541
|
+
const documentTitle = document.title?.trim() ?? "";
|
|
1542
|
+
const declaredLinks = discoverDeclaredWebLinks(
|
|
1543
|
+
document as unknown as Document,
|
|
1544
|
+
response.headers.get("link"),
|
|
1545
|
+
response.url || url,
|
|
1546
|
+
);
|
|
1547
|
+
const { Readability } = await import("@mozilla/readability");
|
|
1548
|
+
const reader = new Readability(document as unknown as Document);
|
|
1549
|
+
const article = reader.parse();
|
|
1550
|
+
|
|
1551
|
+
if (!article) {
|
|
1552
|
+
const rscResult = extractRSCContent(text);
|
|
1553
|
+
if (rscResult && rscResult.content.length >= MIN_USEFUL_CONTENT) {
|
|
1554
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
1555
|
+
return {
|
|
1556
|
+
url,
|
|
1557
|
+
title: rscResult.title,
|
|
1558
|
+
content: appendDeclaredWebLinks(rscResult.content, declaredLinks),
|
|
1559
|
+
error: null,
|
|
1560
|
+
declaredLinks,
|
|
1561
|
+
};
|
|
1562
|
+
}
|
|
1563
|
+
controller.signal.throwIfAborted();
|
|
1564
|
+
const defuddleResult = await extractWithDefuddle(text, response.url || url);
|
|
1565
|
+
controller.signal.throwIfAborted();
|
|
1566
|
+
if (defuddleResult && defuddleResult.content.length >= MIN_USEFUL_CONTENT) {
|
|
1567
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
1568
|
+
return {
|
|
1569
|
+
url,
|
|
1570
|
+
title: documentTitle || defuddleResult.title,
|
|
1571
|
+
content: appendDeclaredWebLinks(defuddleResult.content, declaredLinks),
|
|
1572
|
+
error: null,
|
|
1573
|
+
declaredLinks,
|
|
1574
|
+
};
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
1578
|
+
const jsRendered = isLikelyJSRendered(text);
|
|
1579
|
+
const errorMsg = jsRendered
|
|
1580
|
+
? "Page appears to be JavaScript-rendered (content loads dynamically)"
|
|
1581
|
+
: "Could not extract readable content from HTML structure";
|
|
1582
|
+
|
|
1583
|
+
return {
|
|
1584
|
+
url,
|
|
1585
|
+
title: documentTitle,
|
|
1586
|
+
content: appendDeclaredWebLinks("", declaredLinks),
|
|
1587
|
+
error: errorMsg,
|
|
1588
|
+
declaredLinks,
|
|
1589
|
+
};
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
if (typeof article.content !== "string") {
|
|
1593
|
+
throw new Error("Readability returned invalid article content");
|
|
1594
|
+
}
|
|
1595
|
+
const markdown = (await getTurndown()).turndown(article.content);
|
|
1596
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
1597
|
+
|
|
1598
|
+
if (markdown.length < MIN_USEFUL_CONTENT) {
|
|
1599
|
+
const rscResult = extractRSCContent(text);
|
|
1600
|
+
if (rscResult && rscResult.content.length >= MIN_USEFUL_CONTENT) {
|
|
1601
|
+
return {
|
|
1602
|
+
url,
|
|
1603
|
+
title: rscResult.title,
|
|
1604
|
+
content: appendDeclaredWebLinks(rscResult.content, declaredLinks),
|
|
1605
|
+
error: null,
|
|
1606
|
+
declaredLinks,
|
|
1607
|
+
};
|
|
1608
|
+
}
|
|
1609
|
+
controller.signal.throwIfAborted();
|
|
1610
|
+
const defuddleResult = await extractWithDefuddle(text, response.url || url);
|
|
1611
|
+
controller.signal.throwIfAborted();
|
|
1612
|
+
if (defuddleResult && defuddleResult.content.length >= MIN_USEFUL_CONTENT) {
|
|
1613
|
+
return {
|
|
1614
|
+
url,
|
|
1615
|
+
title: article.title || documentTitle || defuddleResult.title,
|
|
1616
|
+
content: appendDeclaredWebLinks(defuddleResult.content, declaredLinks),
|
|
1617
|
+
error: null,
|
|
1618
|
+
declaredLinks,
|
|
1619
|
+
};
|
|
1620
|
+
}
|
|
1621
|
+
let error: string | null = "Page appears to be JavaScript-rendered (content loads dynamically)";
|
|
1622
|
+
if (!isLikelyJSRendered(text)) {
|
|
1623
|
+
// Readability mutated `document`, so measure the page's own visible text
|
|
1624
|
+
// from a fresh parse. A static page whose whole body is under the floor
|
|
1625
|
+
// is complete once something was extracted from it; any executable
|
|
1626
|
+
// script means the text may be a placeholder for client rendering.
|
|
1627
|
+
const { document: original } = parseHTML(text);
|
|
1628
|
+
const hasExecutableScript = [...original.querySelectorAll("script")]
|
|
1629
|
+
.some((script) => isExecutableScriptType(script.getAttribute("type")));
|
|
1630
|
+
const visibleChars = visibleTextLength(original);
|
|
1631
|
+
const extractedChars = markdown.trim().length;
|
|
1632
|
+
const counts = `Extracted content appears incomplete: extracted ${extractedChars} characters from a page with ${visibleChars} characters of visible text`;
|
|
1633
|
+
if (visibleChars >= MIN_USEFUL_CONTENT) error = counts;
|
|
1634
|
+
else if (hasExecutableScript) error = `Extracted content appears incomplete: the page has only ${visibleChars} characters of visible text and runs scripts, so content may load dynamically`;
|
|
1635
|
+
else error = extractedChars > 0 ? null : counts;
|
|
1636
|
+
}
|
|
1637
|
+
return {
|
|
1638
|
+
url,
|
|
1639
|
+
title: article.title || documentTitle,
|
|
1640
|
+
content: appendDeclaredWebLinks(markdown, declaredLinks),
|
|
1641
|
+
error,
|
|
1642
|
+
declaredLinks,
|
|
1643
|
+
};
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
// Readability can keep one block of a page (one section of a guide, a
|
|
1647
|
+
// product page's cart drawer) and still clear the length floor. The
|
|
1648
|
+
// thresholds were measured on #673's examples (coverage <= 0.25, gain
|
|
1649
|
+
// >= 1.9x) and ordinary articles and docs (coverage >= 0.55, gain <= 1.2x).
|
|
1650
|
+
// Readability's result already stands, so a Defuddle failure keeps it.
|
|
1651
|
+
const extractedText = markdownTextLength(markdown);
|
|
1652
|
+
if (extractedText < visibleTextLength(parseHTML(text).document) * 0.5) {
|
|
1653
|
+
controller.signal.throwIfAborted();
|
|
1654
|
+
const defuddleResult = await extractWithDefuddle(text, response.url || url).catch(() => null);
|
|
1655
|
+
controller.signal.throwIfAborted();
|
|
1656
|
+
if (defuddleResult && defuddleResult.content.length >= MIN_USEFUL_CONTENT && markdownTextLength(defuddleResult.content) >= extractedText * 1.5) {
|
|
1657
|
+
return {
|
|
1658
|
+
url,
|
|
1659
|
+
title: article.title || documentTitle || defuddleResult.title,
|
|
1660
|
+
content: appendDeclaredWebLinks(defuddleResult.content, declaredLinks),
|
|
1661
|
+
error: null,
|
|
1662
|
+
declaredLinks,
|
|
1663
|
+
};
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
|
|
1667
|
+
return {
|
|
1668
|
+
url,
|
|
1669
|
+
title: article.title || documentTitle,
|
|
1670
|
+
content: appendDeclaredWebLinks(markdown, declaredLinks),
|
|
1671
|
+
error: null,
|
|
1672
|
+
declaredLinks,
|
|
1673
|
+
};
|
|
1674
|
+
} catch (err) {
|
|
1675
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1676
|
+
if (message.toLowerCase().includes("abort")) {
|
|
1677
|
+
activityMonitor.logComplete(activityId, 0);
|
|
1678
|
+
} else {
|
|
1679
|
+
activityMonitor.logError(activityId, message);
|
|
1680
|
+
}
|
|
1681
|
+
return { url, title: "", content: "", error: message };
|
|
1682
|
+
} finally {
|
|
1683
|
+
clearTimeout(timeoutId);
|
|
1684
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1685
|
+
// Imports and CPU-bound processing need not observe the fetch signal, and
|
|
1686
|
+
// can finish before an expired timer gets a turn. Guard every exit, with
|
|
1687
|
+
// caller cancellation taking precedence over the internal deadline.
|
|
1688
|
+
if (signal?.aborted) return abortedResult(url);
|
|
1689
|
+
if (controller.signal.aborted || Date.now() - startedAt >= timeoutMs) {
|
|
1690
|
+
return { url, title: "", content: "", error: "The operation was aborted." };
|
|
1691
|
+
}
|
|
1692
|
+
}
|
|
1693
|
+
}
|
|
1694
|
+
|
|
1695
|
+
export function extractHeadingTitle(text: string): string | null {
|
|
1696
|
+
const match = text.match(/^#{1,2}\s+(.+)/m);
|
|
1697
|
+
if (!match) return null;
|
|
1698
|
+
const cleaned = match[1].replace(/\*+/g, "").trim();
|
|
1699
|
+
return cleaned || null;
|
|
1700
|
+
}
|
|
1701
|
+
|
|
1702
|
+
function extractTextTitle(text: string, url: string): string {
|
|
1703
|
+
return extractHeadingTitle(text) ?? (new URL(url).pathname.split("/").pop() || url);
|
|
1704
|
+
}
|
|
1705
|
+
|
|
1706
|
+
export async function fetchAllContent(
|
|
1707
|
+
urls: string[],
|
|
1708
|
+
signal?: AbortSignal,
|
|
1709
|
+
options?: ExtractOptions,
|
|
1710
|
+
): Promise<ExtractedContent[]> {
|
|
1711
|
+
const results = await Promise.all(urls.map((url) => fetchLimit(() => extractContent(url, signal, options))));
|
|
1712
|
+
if (options?.mode === "raw") return results;
|
|
1713
|
+
// Inline data: URIs in extracted markdown would otherwise flow into tool
|
|
1714
|
+
// results and the fetch cache as opaque base64; typed thumbnail/frame image
|
|
1715
|
+
// blocks are deliberate outputs and are left untouched.
|
|
1716
|
+
return results.map((result, index) => {
|
|
1717
|
+
if (!result.content) return result;
|
|
1718
|
+
const sanitized = sanitizeInlineDataUris(result.content, `urls[${index}].content`);
|
|
1719
|
+
return sanitized.omissions.length > 0 ? { ...result, content: sanitized.text } : result;
|
|
1720
|
+
});
|
|
1721
|
+
}
|