@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
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { activityMonitor } from "./activity.ts";
|
|
3
|
+
import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
|
|
4
|
+
import { normalizeDomain } from "./domain-filter-normalization.ts";
|
|
5
|
+
import type { SearchOptions, SearchResponse } from "./perplexity.ts";
|
|
6
|
+
import { formatSearchResultsAsAnswer } from "./search-answer-formatting.ts";
|
|
7
|
+
import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
|
|
8
|
+
import { fetchWithCredentialRedirects, getWebSearchConfigPath } from "./utils.ts";
|
|
9
|
+
|
|
10
|
+
// Cloudflare Web Search API (https://developers.cloudflare.com/web-search/): one endpoint that
|
|
11
|
+
// runs a query on Ceramic, Exa, or Linkup through an AI Gateway and returns one result shape.
|
|
12
|
+
const CONFIG_PATH = getWebSearchConfigPath();
|
|
13
|
+
const SEARCH_TIMEOUT_MS = 30_000;
|
|
14
|
+
const MAX_REQUEST_RESULTS = 10;
|
|
15
|
+
// The API rejects longer queries. String length counts UTF-16 units, which is never less than
|
|
16
|
+
// the Unicode character count, so a query that passes this check is not too long either way.
|
|
17
|
+
const MAX_QUERY_CHARS = 1024;
|
|
18
|
+
const MAX_SNIPPET_CHARS = 500;
|
|
19
|
+
const DEFAULT_GATEWAY_ID = "default";
|
|
20
|
+
export const CLOUDFLARE_SEARCH_PROVIDERS = ["ceramic", "exa", "linkup"] as const;
|
|
21
|
+
type CloudflareSearchProvider = typeof CLOUDFLARE_SEARCH_PROVIDERS[number];
|
|
22
|
+
|
|
23
|
+
interface WebSearchConfig {
|
|
24
|
+
cloudflareApiKey?: unknown;
|
|
25
|
+
cloudflareAccountId?: unknown;
|
|
26
|
+
cloudflareGatewayId?: unknown;
|
|
27
|
+
cloudflareSearchProvider?: unknown;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface CloudflareSearchItem {
|
|
31
|
+
url?: unknown;
|
|
32
|
+
title?: unknown;
|
|
33
|
+
description?: unknown;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
let cachedConfig: WebSearchConfig | null = null;
|
|
37
|
+
|
|
38
|
+
function loadConfig(): WebSearchConfig {
|
|
39
|
+
if (cachedConfig) return cachedConfig;
|
|
40
|
+
if (!existsSync(CONFIG_PATH)) {
|
|
41
|
+
cachedConfig = {};
|
|
42
|
+
return cachedConfig;
|
|
43
|
+
}
|
|
44
|
+
let parsed: unknown;
|
|
45
|
+
// JSON parse errors can quote credentials from the file, so they are not echoed.
|
|
46
|
+
try { parsed = JSON.parse(readFileSync(CONFIG_PATH, "utf-8")); } catch { parsed = undefined; }
|
|
47
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);
|
|
48
|
+
cachedConfig = parsed as WebSearchConfig;
|
|
49
|
+
return cachedConfig;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function setting(envValue: string | undefined, configValue: unknown, name: string): string | undefined {
|
|
53
|
+
const value = envValue?.trim() ? envValue : configValue;
|
|
54
|
+
if (value === undefined || value === null || value === "") return undefined;
|
|
55
|
+
if (typeof value !== "string") throw new Error(`${name} in ${CONFIG_PATH} must be a string`);
|
|
56
|
+
return value.trim() || undefined;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function accountId(): string | undefined {
|
|
60
|
+
return setting(process.env.CLOUDFLARE_ACCOUNT_ID, loadConfig().cloudflareAccountId, "cloudflareAccountId");
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function gatewayId(): string {
|
|
64
|
+
return setting(process.env.CLOUDFLARE_GATEWAY_ID, loadConfig().cloudflareGatewayId, "cloudflareGatewayId") ?? DEFAULT_GATEWAY_ID;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function searchProvider(): CloudflareSearchProvider {
|
|
68
|
+
const value = setting(process.env.CLOUDFLARE_SEARCH_PROVIDER, loadConfig().cloudflareSearchProvider, "cloudflareSearchProvider") ?? "ceramic";
|
|
69
|
+
const provider = value.toLowerCase();
|
|
70
|
+
if (!(CLOUDFLARE_SEARCH_PROVIDERS as readonly string[]).includes(provider)) {
|
|
71
|
+
throw new Error(`cloudflareSearchProvider must be one of ${CLOUDFLARE_SEARCH_PROVIDERS.join(", ")}; got ${JSON.stringify(value)}`);
|
|
72
|
+
}
|
|
73
|
+
return provider as CloudflareSearchProvider;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function isCloudflareSearchAvailable(): boolean {
|
|
77
|
+
return !!accountId() && hasCredentialSource({ provider: "Cloudflare", configuredValue: loadConfig().cloudflareApiKey, environmentValue: process.env.CLOUDFLARE_API_KEY });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
interface DomainFilters {
|
|
81
|
+
include: string[];
|
|
82
|
+
exclude: string[];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function parseDomainFilter(domainFilter: string[] | undefined): DomainFilters {
|
|
86
|
+
const filters: DomainFilters = { include: [], exclude: [] };
|
|
87
|
+
for (const raw of domainFilter ?? []) {
|
|
88
|
+
const domain = normalizeDomain(raw);
|
|
89
|
+
if (!domain) continue;
|
|
90
|
+
const target = raw.trim().startsWith("-") ? filters.exclude : filters.include;
|
|
91
|
+
if (!target.includes(domain)) target.push(domain);
|
|
92
|
+
}
|
|
93
|
+
return filters;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function passesDomainFilters(url: URL, filters: DomainFilters): boolean {
|
|
97
|
+
const hostname = url.hostname.toLowerCase();
|
|
98
|
+
const matches = (domain: string) => hostname === domain || hostname.endsWith(`.${domain}`);
|
|
99
|
+
if (filters.exclude.some(matches)) return false;
|
|
100
|
+
return filters.include.length === 0 || filters.include.some(matches);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// The API has no domain parameters. Ceramic documents `site:` with `OR`, so allowed domains go
|
|
104
|
+
// into its query; for every provider the returned results are filtered locally as well.
|
|
105
|
+
// A query over the limit fails here instead of being cut, since cutting can break a `site:` clause.
|
|
106
|
+
function buildQuery(query: string, provider: CloudflareSearchProvider, filters: DomainFilters): string {
|
|
107
|
+
const sites = provider === "ceramic" ? filters.include.map(domain => `site:${domain}`) : [];
|
|
108
|
+
const built = sites.length === 0 ? query : `${query} ${sites.length === 1 ? sites[0] : `(${sites.join(" OR ")})`}`;
|
|
109
|
+
if (built.length > MAX_QUERY_CHARS) {
|
|
110
|
+
throw new Error(`Cloudflare Web Search invalid request: the query is ${built.length} characters${sites.length > 0 ? " with domain filters" : ""}; Cloudflare Web Search accepts at most ${MAX_QUERY_CHARS}`);
|
|
111
|
+
}
|
|
112
|
+
return built;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function text(value: unknown): string {
|
|
116
|
+
return typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "";
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
120
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Error bodies come in three shapes (see cloudflare/agents packages/agents/src/web/search/source.ts):
|
|
124
|
+
// gateway `{ ok: false, error: { code, status } }`, validation `{ success: false, errors: [{ message }],
|
|
125
|
+
// messages: [{ message, path }] }`, and gateway setup `{ success: false, error: [{ message }], message }`.
|
|
126
|
+
function describeError(status: number, body: string): { status: number; detail: string } {
|
|
127
|
+
let parsed: unknown;
|
|
128
|
+
try { parsed = JSON.parse(body); } catch { return { status, detail: body }; }
|
|
129
|
+
if (!isRecord(parsed)) return { status, detail: body };
|
|
130
|
+
const error = parsed.error;
|
|
131
|
+
if (isRecord(error) && typeof error.code === "string") {
|
|
132
|
+
const errorStatus = typeof error.status === "number" ? error.status : status;
|
|
133
|
+
// Newer responses carry a readable `message` that says how to fix the problem.
|
|
134
|
+
if (text(error.message)) return { status: errorStatus, detail: `${error.code}: ${text(error.message)}` };
|
|
135
|
+
const hint = error.code === "web_search_payment_required"
|
|
136
|
+
? " (no AI Gateway credits and no provider key stored on the gateway)"
|
|
137
|
+
: error.code === "web_search_gateway_not_configured" ? " (create the AI Gateway or set cloudflareGatewayId)" : "";
|
|
138
|
+
return { status: errorStatus, detail: `${error.code}${hint}` };
|
|
139
|
+
}
|
|
140
|
+
const entries = [...(Array.isArray(parsed.errors) ? parsed.errors : []), ...(Array.isArray(error) ? error : [])];
|
|
141
|
+
const issues = Array.isArray(parsed.messages) ? parsed.messages : [];
|
|
142
|
+
const parts = [
|
|
143
|
+
...entries.map(entry => isRecord(entry) ? text(entry.message) : ""),
|
|
144
|
+
...issues.map(issue => {
|
|
145
|
+
if (!isRecord(issue) || !text(issue.message)) return "";
|
|
146
|
+
return Array.isArray(issue.path) && issue.path.length ? `${issue.path.join(".")}: ${text(issue.message)}` : text(issue.message);
|
|
147
|
+
}),
|
|
148
|
+
].filter(Boolean);
|
|
149
|
+
return { status, detail: parts.join("; ") || text(parsed.message) || body };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function parseItems(value: unknown): CloudflareSearchItem[] {
|
|
153
|
+
// The documented success body is `{ items, metadata }`; accept the v4 `{ result }` envelope too.
|
|
154
|
+
const body = isRecord(value) && isRecord(value.result) && !Array.isArray(value.items) ? value.result : value;
|
|
155
|
+
if (!isRecord(body) || !Array.isArray(body.items)) throw new Error("Cloudflare Web Search returned invalid response: expected items array");
|
|
156
|
+
return body.items as CloudflareSearchItem[];
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// The API has no date filter, so `recencyFilter` is not applied.
|
|
160
|
+
export async function searchWithCloudflare(query: string, options: SearchOptions = {}): Promise<SearchResponse> {
|
|
161
|
+
const account = accountId();
|
|
162
|
+
if (!account) {
|
|
163
|
+
throw new Error(
|
|
164
|
+
"Cloudflare account ID not found. Set cloudflareAccountId in " + CONFIG_PATH + " or CLOUDFLARE_ACCOUNT_ID, " +
|
|
165
|
+
"with cloudflareApiKey or CLOUDFLARE_API_KEY (an API token with Workers AI Read and AI Gateway Read)",
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
const apiKey = await resolveCredential({ provider: "Cloudflare", configuredValue: loadConfig().cloudflareApiKey, environmentValue: process.env.CLOUDFLARE_API_KEY, signal: options.signal });
|
|
169
|
+
if (!apiKey) {
|
|
170
|
+
throw new Error(
|
|
171
|
+
"Cloudflare API key not found. Set cloudflareApiKey in " + CONFIG_PATH + " or CLOUDFLARE_API_KEY " +
|
|
172
|
+
"to an API token with Workers AI Read and AI Gateway Read",
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
const provider = searchProvider();
|
|
176
|
+
const numResults = normalizeSearchResultCount(options.numResults);
|
|
177
|
+
const filters = parseDomainFilter(options.domainFilter);
|
|
178
|
+
const hasDomainFilters = filters.include.length > 0 || filters.exclude.length > 0;
|
|
179
|
+
const body = {
|
|
180
|
+
query: buildQuery(query, provider, filters),
|
|
181
|
+
provider,
|
|
182
|
+
// Results are filtered locally when domains are set, so ask for the most the API allows.
|
|
183
|
+
limit: hasDomainFilters ? MAX_REQUEST_RESULTS : Math.min(MAX_REQUEST_RESULTS, numResults),
|
|
184
|
+
options: { gateway: { id: gatewayId() } },
|
|
185
|
+
};
|
|
186
|
+
const url = `https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(account)}/ai/websearch/`;
|
|
187
|
+
const activityId = activityMonitor.logStart({ type: "api", query });
|
|
188
|
+
const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
|
|
189
|
+
let status = 0;
|
|
190
|
+
let items: CloudflareSearchItem[];
|
|
191
|
+
try {
|
|
192
|
+
const response = await fetchWithCredentialRedirects(url, {
|
|
193
|
+
method: "POST",
|
|
194
|
+
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", Accept: "application/json" },
|
|
195
|
+
body: JSON.stringify(body),
|
|
196
|
+
signal: options.signal ? AbortSignal.any([timeout, options.signal]) : timeout,
|
|
197
|
+
}, ["Authorization"]);
|
|
198
|
+
status = response.status;
|
|
199
|
+
if (!response.ok) {
|
|
200
|
+
const error = describeError(response.status, await response.text());
|
|
201
|
+
// The status stays in the message so searchRouting can classify quota and transient failures.
|
|
202
|
+
throw new Error(`Cloudflare Web Search error ${error.status}: ${redactCredential(error.detail, apiKey).slice(0, 300)}`);
|
|
203
|
+
}
|
|
204
|
+
// Syntax errors can quote the body, so they are not echoed.
|
|
205
|
+
const data = await response.json().catch((err: unknown) => { throw err instanceof SyntaxError ? new Error("Cloudflare Web Search returned invalid JSON") : err; });
|
|
206
|
+
items = parseItems(data);
|
|
207
|
+
} catch (err) {
|
|
208
|
+
// Node reports the deadline as "aborted due to timeout", which routing would treat as a cancellation.
|
|
209
|
+
if (!options.signal?.aborted && (timeout.aborted || (err instanceof Error && err.name === "TimeoutError"))) {
|
|
210
|
+
const message = `Cloudflare Web Search request timed out after ${SEARCH_TIMEOUT_MS / 1000}s`;
|
|
211
|
+
activityMonitor.logError(activityId, message);
|
|
212
|
+
throw new Error(message);
|
|
213
|
+
}
|
|
214
|
+
const message = redactCredential(err instanceof Error ? err.message : String(err), apiKey);
|
|
215
|
+
activityMonitor.logError(activityId, message);
|
|
216
|
+
if (err instanceof Error && err.message === message) throw err;
|
|
217
|
+
throw new Error(message);
|
|
218
|
+
}
|
|
219
|
+
activityMonitor.logComplete(activityId, status);
|
|
220
|
+
const results: SearchResponse["results"] = [];
|
|
221
|
+
const seen = new Set<string>();
|
|
222
|
+
for (const item of items) {
|
|
223
|
+
if (!isRecord(item) || typeof item.url !== "string") continue;
|
|
224
|
+
let resultUrl: URL;
|
|
225
|
+
try { resultUrl = new URL(item.url.trim()); } catch { continue; }
|
|
226
|
+
if (resultUrl.protocol !== "http:" && resultUrl.protocol !== "https:") continue;
|
|
227
|
+
if (!passesDomainFilters(resultUrl, filters) || seen.has(resultUrl.href)) continue;
|
|
228
|
+
seen.add(resultUrl.href);
|
|
229
|
+
results.push({
|
|
230
|
+
title: text(item.title) || resultUrl.href,
|
|
231
|
+
url: resultUrl.href,
|
|
232
|
+
snippet: text(item.description).slice(0, MAX_SNIPPET_CHARS),
|
|
233
|
+
});
|
|
234
|
+
if (results.length >= numResults) break;
|
|
235
|
+
}
|
|
236
|
+
return { answer: formatSearchResultsAsAnswer(results), results };
|
|
237
|
+
}
|
package/content-find.ts
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
export type FindMode = "exact" | "case-insensitive" | "fuzzy";
|
|
2
|
+
|
|
3
|
+
const CONTEXT_CHARS = 400;
|
|
4
|
+
const MAX_OUTPUT_CHARS = 20_000;
|
|
5
|
+
|
|
6
|
+
interface Match {
|
|
7
|
+
query: string;
|
|
8
|
+
start: number;
|
|
9
|
+
end: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
interface Range {
|
|
13
|
+
start: number;
|
|
14
|
+
end: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function normalize(value: string): string {
|
|
18
|
+
return value.normalize("NFD").replace(/\p{Diacritic}/gu, "").toLocaleLowerCase();
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function editDistanceWithin(left: string, right: string, maximum: number): boolean {
|
|
22
|
+
if (Math.abs(left.length - right.length) > maximum) return false;
|
|
23
|
+
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
24
|
+
for (let i = 1; i <= left.length; i++) {
|
|
25
|
+
const current = [i];
|
|
26
|
+
let rowMinimum = i;
|
|
27
|
+
for (let j = 1; j <= right.length; j++) {
|
|
28
|
+
const value = Math.min(
|
|
29
|
+
previous[j] + 1,
|
|
30
|
+
current[j - 1] + 1,
|
|
31
|
+
previous[j - 1] + (left[i - 1] === right[j - 1] ? 0 : 1),
|
|
32
|
+
);
|
|
33
|
+
current[j] = value;
|
|
34
|
+
rowMinimum = Math.min(rowMinimum, value);
|
|
35
|
+
}
|
|
36
|
+
if (rowMinimum > maximum) return false;
|
|
37
|
+
previous = current;
|
|
38
|
+
}
|
|
39
|
+
return previous[right.length] <= maximum;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function literalMatches(text: string, query: string, caseInsensitive: boolean): Match[] {
|
|
43
|
+
const haystack = caseInsensitive ? text.toLocaleLowerCase() : text;
|
|
44
|
+
const needle = caseInsensitive ? query.toLocaleLowerCase() : query;
|
|
45
|
+
const matches: Match[] = [];
|
|
46
|
+
for (let start = haystack.indexOf(needle); start >= 0; start = haystack.indexOf(needle, start + Math.max(needle.length, 1))) {
|
|
47
|
+
matches.push({ query, start, end: start + query.length });
|
|
48
|
+
}
|
|
49
|
+
return matches;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function fuzzyMatches(text: string, query: string): Match[] {
|
|
53
|
+
const queryTokens = normalize(query).match(/[\p{L}\p{N}]+/gu) ?? [];
|
|
54
|
+
if (queryTokens.length === 0) return [];
|
|
55
|
+
const matches: Match[] = [];
|
|
56
|
+
const paragraphs = /[^\n]+(?:\n(?!\n)[^\n]+)*/g;
|
|
57
|
+
for (const paragraph of text.matchAll(paragraphs)) {
|
|
58
|
+
const paragraphText = paragraph[0];
|
|
59
|
+
if (paragraphText.trim().length === 0 || paragraph.index === undefined) continue;
|
|
60
|
+
const tokens = [...paragraphText.matchAll(/[\p{L}\p{N}]+/gu)];
|
|
61
|
+
const matched = queryTokens.filter(queryToken => tokens.some(token => {
|
|
62
|
+
const candidate = normalize(token[0]);
|
|
63
|
+
const maximum = queryToken.length >= 9 ? 2 : queryToken.length >= 5 ? 1 : 0;
|
|
64
|
+
return editDistanceWithin(queryToken, candidate, maximum);
|
|
65
|
+
}));
|
|
66
|
+
const required = queryTokens.length === 1 ? 1 : Math.ceil(queryTokens.length * 0.6);
|
|
67
|
+
if (matched.length < required) continue;
|
|
68
|
+
const first = tokens.find(token => matched.some(queryToken => {
|
|
69
|
+
const maximum = queryToken.length >= 9 ? 2 : queryToken.length >= 5 ? 1 : 0;
|
|
70
|
+
return editDistanceWithin(queryToken, normalize(token[0]), maximum);
|
|
71
|
+
}))!;
|
|
72
|
+
const start = paragraph.index + first.index;
|
|
73
|
+
matches.push({ query, start, end: start + first[0].length });
|
|
74
|
+
}
|
|
75
|
+
return matches;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function mergeRanges(ranges: Range[]): Range[] {
|
|
79
|
+
const merged: Range[] = [];
|
|
80
|
+
for (const range of [...ranges].sort((left, right) => left.start - right.start || left.end - right.end)) {
|
|
81
|
+
const previous = merged.at(-1);
|
|
82
|
+
if (previous && range.start <= previous.end) previous.end = Math.max(previous.end, range.end);
|
|
83
|
+
else merged.push({ ...range });
|
|
84
|
+
}
|
|
85
|
+
return merged;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function contextRanges(textLength: number, matches: Match[]): Range[] {
|
|
89
|
+
const ranges: Range[] = [];
|
|
90
|
+
for (const match of matches) {
|
|
91
|
+
ranges.push({
|
|
92
|
+
start: Math.max(0, match.start - CONTEXT_CHARS),
|
|
93
|
+
end: Math.min(textLength, match.end + CONTEXT_CHARS),
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
return mergeRanges(ranges);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function lowerBound(values: number[], target: number): number {
|
|
100
|
+
let low = 0;
|
|
101
|
+
let high = values.length;
|
|
102
|
+
while (low < high) {
|
|
103
|
+
const middle = (low + high) >>> 1;
|
|
104
|
+
if (values[middle] < target) low = middle + 1;
|
|
105
|
+
else high = middle;
|
|
106
|
+
}
|
|
107
|
+
return low;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function upperBound(values: number[], target: number): number {
|
|
111
|
+
let low = 0;
|
|
112
|
+
let high = values.length;
|
|
113
|
+
while (low < high) {
|
|
114
|
+
const middle = (low + high) >>> 1;
|
|
115
|
+
if (values[middle] <= target) low = middle + 1;
|
|
116
|
+
else high = middle;
|
|
117
|
+
}
|
|
118
|
+
return low;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function findContent(
|
|
122
|
+
text: string,
|
|
123
|
+
queries: string[],
|
|
124
|
+
mode: FindMode,
|
|
125
|
+
): { text: string; matchCount: number; returnedMatches: number; queryResults: Array<{ query: string; matchCount: number }> } {
|
|
126
|
+
const normalizedQueries = [...new Set(queries.map(query => query.trim()).filter(Boolean))];
|
|
127
|
+
const occurrences = normalizedQueries.map(query => {
|
|
128
|
+
const matches = mode === "fuzzy" ? fuzzyMatches(text, query) : literalMatches(text, query, mode === "case-insensitive");
|
|
129
|
+
return { query, matches, starts: matches.map(match => match.start), ends: matches.map(match => match.end) };
|
|
130
|
+
});
|
|
131
|
+
const matches = occurrences.flatMap(result => result.matches);
|
|
132
|
+
const queryResults = occurrences.map(result => ({ query: result.query, matchCount: result.matches.length }));
|
|
133
|
+
|
|
134
|
+
const heading = matches.length > 0 ? `Text matches (${mode})` : `Text matches (${mode}): no matches`;
|
|
135
|
+
const missing = queryResults.filter(result => result.matchCount === 0).map(result => `\"${result.query}\"`);
|
|
136
|
+
const matchingQueries = occurrences.filter(result => result.matches.length > 0).map((result, index) => ({
|
|
137
|
+
...result,
|
|
138
|
+
id: `Q${index + 1}`,
|
|
139
|
+
order: index,
|
|
140
|
+
}));
|
|
141
|
+
const whitespaceRuns = [...text.matchAll(/\s+/g)].map(run => ({ start: run.index, end: run.index + run[0].length }));
|
|
142
|
+
const whitespaceStarts = whitespaceRuns.map(run => run.start);
|
|
143
|
+
const whitespaceEnds = whitespaceRuns.map(run => run.end);
|
|
144
|
+
const whitespaceSavings = [0];
|
|
145
|
+
for (const run of whitespaceRuns) whitespaceSavings.push(whitespaceSavings.at(-1)! + run.end - run.start - 1);
|
|
146
|
+
function normalizedLength(start: number, end: number): number {
|
|
147
|
+
const firstRun = upperBound(whitespaceStarts, start) - 1;
|
|
148
|
+
if (firstRun >= 0 && whitespaceEnds[firstRun] > start) start = whitespaceEnds[firstRun];
|
|
149
|
+
if (start >= end) return 0;
|
|
150
|
+
const lastRun = upperBound(whitespaceStarts, end - 1) - 1;
|
|
151
|
+
if (lastRun >= 0 && whitespaceEnds[lastRun] >= end) end = whitespaceStarts[lastRun];
|
|
152
|
+
if (start >= end) return 0;
|
|
153
|
+
const first = lowerBound(whitespaceStarts, start);
|
|
154
|
+
const last = upperBound(whitespaceEnds, end);
|
|
155
|
+
return end - start - (whitespaceSavings[last] - whitespaceSavings[first]);
|
|
156
|
+
}
|
|
157
|
+
function rangeCounts(range: Range) {
|
|
158
|
+
// Literal occurrences have fixed widths; fuzzy occurrences come from successive disjoint paragraphs.
|
|
159
|
+
return matchingQueries.flatMap(result => {
|
|
160
|
+
const first = lowerBound(result.starts, range.start);
|
|
161
|
+
const last = upperBound(result.ends, range.end);
|
|
162
|
+
return last > first ? [{ ...result, count: last - first, firstStart: result.starts[first] }] : [];
|
|
163
|
+
}).sort((left, right) => left.firstStart - right.firstStart || left.order - right.order);
|
|
164
|
+
}
|
|
165
|
+
const legend = matchingQueries.length > 0
|
|
166
|
+
? `Queries: ${matchingQueries.map(result => `${result.id} = \"${result.query}\"`).join(", ")}`
|
|
167
|
+
: "";
|
|
168
|
+
const missingNotice = missing.length > 0 ? `No matches: ${missing.join(", ")}` : "";
|
|
169
|
+
function measure(ranges: Range[], overflow = false, omitted: string[] = []) {
|
|
170
|
+
let length = heading.length;
|
|
171
|
+
let returnedMatches = 0;
|
|
172
|
+
if (overflow && legend) length += 2 + legend.length;
|
|
173
|
+
for (const [index, range] of ranges.entries()) {
|
|
174
|
+
const counts = rangeCounts(range);
|
|
175
|
+
if (counts.length === 0) continue;
|
|
176
|
+
const labelsLength = counts.reduce((total, result) => total
|
|
177
|
+
+ (overflow ? result.id.length : result.query.length + 2)
|
|
178
|
+
+ 2 + String(result.count).length, 2 * (counts.length - 1));
|
|
179
|
+
const snippetLength = normalizedLength(range.start, range.end)
|
|
180
|
+
+ (range.start > 0 ? 1 : 0) + (range.end < text.length ? 1 : 0);
|
|
181
|
+
length += 2 + String(index + 1).length + 2 + labelsLength + 1 + snippetLength;
|
|
182
|
+
returnedMatches += counts.reduce((total, result) => total + result.count, 0);
|
|
183
|
+
}
|
|
184
|
+
if (missingNotice) length += 2 + missingNotice.length;
|
|
185
|
+
if (omitted.length > 0) length += 2 + `No representative excerpt: ${omitted.join(", ")}.`.length;
|
|
186
|
+
if (returnedMatches < matches.length) length += 2 + `Showing ${returnedMatches} of ${matches.length} matches.`.length;
|
|
187
|
+
return { length, returnedMatches };
|
|
188
|
+
}
|
|
189
|
+
function formatRanges(ranges: Range[], overflow = false, omitted: string[] = []) {
|
|
190
|
+
const sections = [heading];
|
|
191
|
+
let returnedMatches = 0;
|
|
192
|
+
if (overflow && legend) sections.push(legend);
|
|
193
|
+
for (const [index, range] of ranges.entries()) {
|
|
194
|
+
const contained = rangeCounts(range);
|
|
195
|
+
if (contained.length === 0) continue;
|
|
196
|
+
const prefix = range.start > 0 ? "…" : "";
|
|
197
|
+
const suffix = range.end < text.length ? "…" : "";
|
|
198
|
+
const snippet = `${prefix}${text.slice(range.start, range.end)
|
|
199
|
+
.replace(/[\uD800-\uDFFF]/gu, "\uFFFD").replace(/\s+/g, " ").trim()}${suffix}`;
|
|
200
|
+
const counts = contained
|
|
201
|
+
.map(result => `${overflow ? result.id : `\"${result.query}\"`} ×${result.count}`)
|
|
202
|
+
.join(", ");
|
|
203
|
+
sections.push(`${index + 1}. ${counts}\n${snippet}`);
|
|
204
|
+
returnedMatches += contained.reduce((total, result) => total + result.count, 0);
|
|
205
|
+
}
|
|
206
|
+
if (missingNotice) sections.push(missingNotice);
|
|
207
|
+
if (omitted.length > 0) sections.push(`No representative excerpt: ${omitted.join(", ")}.`);
|
|
208
|
+
if (returnedMatches < matches.length) sections.push(`Showing ${returnedMatches} of ${matches.length} matches.`);
|
|
209
|
+
return { text: sections.join("\n\n"), matchCount: matches.length, returnedMatches, queryResults };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const fullRanges = contextRanges(text.length, matches);
|
|
213
|
+
const full = measure(fullRanges);
|
|
214
|
+
if (full.returnedMatches === matches.length && full.length <= MAX_OUTPUT_CHARS) return formatRanges(fullRanges);
|
|
215
|
+
|
|
216
|
+
let ranges: Range[] = [];
|
|
217
|
+
let omitted = matchingQueries.map(result => result.id);
|
|
218
|
+
if (measure(ranges, true, omitted).length > MAX_OUTPUT_CHARS) {
|
|
219
|
+
const text = `${heading}\n\nUnable to format bounded excerpts: query metadata exceeds ${MAX_OUTPUT_CHARS} characters.\n\nShowing 0 of ${matches.length} matches.`;
|
|
220
|
+
return { text, matchCount: matches.length, returnedMatches: 0, queryResults };
|
|
221
|
+
}
|
|
222
|
+
const witnesses: Match[] = [];
|
|
223
|
+
for (const { id, matches: queryMatches } of matchingQueries) {
|
|
224
|
+
const proposedOmitted = omitted.filter(queryId => queryId !== id);
|
|
225
|
+
const currentLength = measure(ranges, true, omitted).length;
|
|
226
|
+
let selected: { witness: Match; ranges: Range[]; cost: number } | undefined;
|
|
227
|
+
for (const witness of queryMatches) {
|
|
228
|
+
const proposedRanges = mergeRanges([...ranges, { start: witness.start, end: witness.end }]);
|
|
229
|
+
const summary = measure(proposedRanges, true, proposedOmitted);
|
|
230
|
+
const candidate = {
|
|
231
|
+
witness,
|
|
232
|
+
ranges: proposedRanges,
|
|
233
|
+
cost: summary.length - currentLength,
|
|
234
|
+
};
|
|
235
|
+
if (summary.length <= MAX_OUTPUT_CHARS && (!selected || candidate.cost < selected.cost
|
|
236
|
+
|| candidate.cost === selected.cost && (witness.start < selected.witness.start
|
|
237
|
+
|| witness.start === selected.witness.start && witness.end < selected.witness.end))) selected = candidate;
|
|
238
|
+
}
|
|
239
|
+
if (selected) {
|
|
240
|
+
ranges = selected.ranges;
|
|
241
|
+
omitted = proposedOmitted;
|
|
242
|
+
witnesses.push(selected.witness);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
for (const witness of witnesses) {
|
|
246
|
+
const proposed = mergeRanges([...ranges, {
|
|
247
|
+
start: Math.max(0, witness.start - CONTEXT_CHARS),
|
|
248
|
+
end: Math.min(text.length, witness.end + CONTEXT_CHARS),
|
|
249
|
+
}]);
|
|
250
|
+
if (measure(proposed, true, omitted).length <= MAX_OUTPUT_CHARS) ranges = proposed;
|
|
251
|
+
}
|
|
252
|
+
const allOccurrences = mergeRanges([...ranges, ...matches.map(match => ({ start: match.start, end: match.end }))]);
|
|
253
|
+
if (measure(allOccurrences, true, omitted).length <= MAX_OUTPUT_CHARS) ranges = allOccurrences;
|
|
254
|
+
return formatRanges(ranges, true, omitted);
|
|
255
|
+
}
|
package/crawl4ai.ts
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { activityMonitor } from "./activity.ts";
|
|
3
|
+
import { redactCredential, resolveCredential } from "./credential-source.ts";
|
|
4
|
+
import type { ExtractedContent, ExtractOptions } from "./extract.ts";
|
|
5
|
+
import { fetchRemoteUrl, loadSsrfConfig, validateRemoteUrl, type Lookup, type SsrfConfig } from "./ssrf-protection.ts";
|
|
6
|
+
import { getWebSearchConfigPath, isLoopbackHostname } from "./utils.ts";
|
|
7
|
+
|
|
8
|
+
const CONFIG_PATH = getWebSearchConfigPath();
|
|
9
|
+
const EXTRACT_TIMEOUT_MS = 60_000;
|
|
10
|
+
const MARKDOWN_FILTER = "fit";
|
|
11
|
+
|
|
12
|
+
export interface Crawl4aiExtractOptions extends Pick<ExtractOptions, "timeoutMs" | "lookup"> {
|
|
13
|
+
ssrf?: SsrfConfig;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
interface Crawl4aiConfig {
|
|
17
|
+
crawl4aiBaseUrl?: unknown;
|
|
18
|
+
crawl4aiApiToken?: unknown;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
let cachedConfig: Crawl4aiConfig | null = null;
|
|
22
|
+
|
|
23
|
+
function loadConfig(): Crawl4aiConfig {
|
|
24
|
+
if (cachedConfig) return cachedConfig;
|
|
25
|
+
if (!existsSync(CONFIG_PATH)) {
|
|
26
|
+
cachedConfig = {};
|
|
27
|
+
return cachedConfig;
|
|
28
|
+
}
|
|
29
|
+
const raw = readFileSync(CONFIG_PATH, "utf8");
|
|
30
|
+
let parsed: unknown;
|
|
31
|
+
try {
|
|
32
|
+
parsed = JSON.parse(raw);
|
|
33
|
+
} catch (err) {
|
|
34
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
35
|
+
throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
|
|
36
|
+
}
|
|
37
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
38
|
+
throw new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);
|
|
39
|
+
}
|
|
40
|
+
cachedConfig = parsed as Crawl4aiConfig;
|
|
41
|
+
return cachedConfig;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function clearCrawl4aiConfigCache(): void {
|
|
45
|
+
cachedConfig = null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function normalizeBaseUrl(value: unknown): string | null {
|
|
49
|
+
if (typeof value !== "string") return null;
|
|
50
|
+
const trimmed = value.trim();
|
|
51
|
+
if (!trimmed) return null;
|
|
52
|
+
let parsed: URL;
|
|
53
|
+
try {
|
|
54
|
+
parsed = new URL(trimmed);
|
|
55
|
+
} catch {
|
|
56
|
+
throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH}: expected an HTTP or HTTPS URL`);
|
|
57
|
+
}
|
|
58
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
59
|
+
throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH}: expected an HTTP or HTTPS URL`);
|
|
60
|
+
}
|
|
61
|
+
if (parsed.username || parsed.password) {
|
|
62
|
+
throw new Error(`Invalid Crawl4AI base URL in ${CONFIG_PATH}: URL credentials are not allowed`);
|
|
63
|
+
}
|
|
64
|
+
parsed.pathname = parsed.pathname.replace(/\/+$/, "");
|
|
65
|
+
parsed.search = "";
|
|
66
|
+
parsed.hash = "";
|
|
67
|
+
return parsed.toString().replace(/\/+$/, "");
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function getBaseUrl(): string | null {
|
|
71
|
+
return normalizeBaseUrl(process.env.CRAWL4AI_BASE_URL) ?? normalizeBaseUrl(loadConfig().crawl4aiBaseUrl);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function requireBaseUrl(): string {
|
|
75
|
+
const baseUrl = getBaseUrl();
|
|
76
|
+
if (!baseUrl) {
|
|
77
|
+
throw new Error(
|
|
78
|
+
"Crawl4AI base URL not configured. Either:\n" +
|
|
79
|
+
` 1. Set crawl4aiBaseUrl in ${CONFIG_PATH}\n` +
|
|
80
|
+
" 2. Set CRAWL4AI_BASE_URL environment variable",
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
return baseUrl;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function getApiToken(signal?: AbortSignal): Promise<string | null> {
|
|
87
|
+
return resolveCredential({
|
|
88
|
+
provider: "Crawl4AI",
|
|
89
|
+
configuredValue: loadConfig().crawl4aiApiToken,
|
|
90
|
+
environmentValue: process.env.CRAWL4AI_API_TOKEN,
|
|
91
|
+
signal,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function requestSignal(timeoutMs: number, signal?: AbortSignal): AbortSignal {
|
|
96
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
97
|
+
return signal ? AbortSignal.any([timeout, signal]) : timeout;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function errorMessage(err: unknown): string {
|
|
101
|
+
return err instanceof Error ? err.message : String(err);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function isAbortException(err: unknown): boolean {
|
|
105
|
+
return err instanceof DOMException && (err.name === "AbortError" || err.name === "TimeoutError");
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function ssrfOptions(options?: Crawl4aiExtractOptions): SsrfConfig & { lookup?: Lookup } {
|
|
109
|
+
return {
|
|
110
|
+
...(options?.ssrf ?? loadSsrfConfig()),
|
|
111
|
+
...(options?.lookup ? { lookup: options.lookup } : {}),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function firstHeadingTitle(markdown: string): string {
|
|
116
|
+
return /^[ \t]*#[ \t]+(\S.*?)[ \t\r]*$/m.exec(markdown)?.[1] ?? "";
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function isCrawl4aiAvailable(): boolean {
|
|
120
|
+
return getBaseUrl() !== null;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export async function extractWithCrawl4ai(
|
|
124
|
+
url: string,
|
|
125
|
+
signal?: AbortSignal,
|
|
126
|
+
options?: Crawl4aiExtractOptions,
|
|
127
|
+
): Promise<ExtractedContent | null> {
|
|
128
|
+
const baseUrl = requireBaseUrl();
|
|
129
|
+
const ssrf = ssrfOptions(options);
|
|
130
|
+
await validateRemoteUrl(url, ssrf);
|
|
131
|
+
const token = await getApiToken(signal);
|
|
132
|
+
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
|
133
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
134
|
+
const requestUrl = new URL(`${baseUrl}/md`);
|
|
135
|
+
const init = {
|
|
136
|
+
method: "POST",
|
|
137
|
+
headers,
|
|
138
|
+
body: JSON.stringify({ url, f: MARKDOWN_FILTER }),
|
|
139
|
+
signal: requestSignal(options?.timeoutMs ?? EXTRACT_TIMEOUT_MS, signal),
|
|
140
|
+
};
|
|
141
|
+
let seeOther = false;
|
|
142
|
+
const activityId = activityMonitor.logStart({ type: "fetch", url: requestUrl.toString() });
|
|
143
|
+
try {
|
|
144
|
+
const response = await fetchRemoteUrl(requestUrl, init, {
|
|
145
|
+
...ssrf,
|
|
146
|
+
allowLoopback: isLoopbackHostname(requestUrl.hostname),
|
|
147
|
+
onRedirect: ({ to, init: redirectInit, response }) => {
|
|
148
|
+
if (to.origin !== requestUrl.origin) {
|
|
149
|
+
throw new Error(`Crawl4AI refused cross-origin redirect to ${to.origin}`);
|
|
150
|
+
}
|
|
151
|
+
// 303 genuinely means "GET the other resource", and it is final: once a hop has turned the
|
|
152
|
+
// chain into a GET, no later hop may resurrect the extraction body.
|
|
153
|
+
if (response.status === 303) seeOther = true;
|
|
154
|
+
// 301/302 are the hops a reverse proxy in front of a self-hosted instance actually emits, and
|
|
155
|
+
// fetchRemoteUrl turns those into a bodyless GET that /md cannot serve, so replay the POST.
|
|
156
|
+
// 307/308 already keep the method, so their init needs no help.
|
|
157
|
+
const replayPost = !seeOther && (response.status === 301 || response.status === 302);
|
|
158
|
+
return replayPost ? init : redirectInit;
|
|
159
|
+
},
|
|
160
|
+
});
|
|
161
|
+
if (!response.ok) {
|
|
162
|
+
const text = await response.text().catch(() => "");
|
|
163
|
+
throw new Error(`Crawl4AI md error ${response.status}: ${redactCredential(text, token).slice(0, 300)}`);
|
|
164
|
+
}
|
|
165
|
+
let data: unknown;
|
|
166
|
+
try {
|
|
167
|
+
data = await response.json();
|
|
168
|
+
} catch {
|
|
169
|
+
// The parser message quotes the offending body, which can echo the configured token, so it never
|
|
170
|
+
// reaches the thrown error or the activity log.
|
|
171
|
+
throw new Error("Crawl4AI md returned invalid JSON");
|
|
172
|
+
}
|
|
173
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) {
|
|
174
|
+
throw new Error("Crawl4AI md returned an unexpected response shape");
|
|
175
|
+
}
|
|
176
|
+
const envelope = data as Record<string, unknown>;
|
|
177
|
+
if (envelope.success === false) {
|
|
178
|
+
const detail = typeof envelope.error === "string" ? envelope.error : typeof envelope.detail === "string" ? envelope.detail : "";
|
|
179
|
+
throw new Error(`Crawl4AI md unsuccessful: ${redactCredential(detail.trim() || "unknown error", token)}`);
|
|
180
|
+
}
|
|
181
|
+
if (envelope.success !== true) {
|
|
182
|
+
throw new Error("Crawl4AI md returned an unexpected response shape");
|
|
183
|
+
}
|
|
184
|
+
if (typeof envelope.markdown !== "string") {
|
|
185
|
+
throw new Error("Crawl4AI md returned markdown in an unexpected shape");
|
|
186
|
+
}
|
|
187
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
188
|
+
const content = envelope.markdown.trim();
|
|
189
|
+
if (!content) return null;
|
|
190
|
+
return { url, title: firstHeadingTitle(content), content, error: null };
|
|
191
|
+
} catch (err) {
|
|
192
|
+
if (signal?.aborted || isAbortException(err)) activityMonitor.logComplete(activityId, 0);
|
|
193
|
+
else activityMonitor.logError(activityId, errorMessage(err));
|
|
194
|
+
throw err;
|
|
195
|
+
}
|
|
196
|
+
}
|