@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.
Files changed (201) hide show
  1. package/ASTACK.md +23 -0
  2. package/CHANGELOG.md +1289 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1215 -2
  5. package/SECURITY.md +5 -0
  6. package/abortable.ts +17 -0
  7. package/activity.ts +101 -0
  8. package/anysearch.ts +188 -0
  9. package/auth-fetch.ts +152 -0
  10. package/baizhi.ts +124 -0
  11. package/banner.png +0 -0
  12. package/bocha.ts +203 -0
  13. package/brave-rate-limit.ts +176 -0
  14. package/brave.ts +247 -0
  15. package/brightdata-unlocker.ts +272 -0
  16. package/ceramic.ts +220 -0
  17. package/chrome-cookies.ts +752 -0
  18. package/cloudflare-search.ts +237 -0
  19. package/content-find.ts +255 -0
  20. package/crawl4ai.ts +196 -0
  21. package/credential-source.ts +242 -0
  22. package/curator-page.ts +3607 -0
  23. package/curator-run.ts +45 -0
  24. package/curator-server.ts +761 -0
  25. package/custom-search.ts +226 -0
  26. package/data-uri-sanitize.ts +406 -0
  27. package/datalab-pdf-extract.ts +568 -0
  28. package/declared-web-links.ts +173 -0
  29. package/deepseek.ts +377 -0
  30. package/degoog.ts +323 -0
  31. package/dist/index.js +28286 -0
  32. package/dist/mcp-cli.js +29186 -0
  33. package/dist/pi-mcp.js +20855 -0
  34. package/dist/types/abortable.d.ts +2 -0
  35. package/dist/types/activity.d.ts +33 -0
  36. package/dist/types/anysearch.d.ts +7 -0
  37. package/dist/types/auth-fetch.d.ts +14 -0
  38. package/dist/types/baizhi.d.ts +3 -0
  39. package/dist/types/bocha.d.ts +3 -0
  40. package/dist/types/brave-rate-limit.d.ts +35 -0
  41. package/dist/types/brave.d.ts +3 -0
  42. package/dist/types/brightdata-unlocker.d.ts +11 -0
  43. package/dist/types/ceramic.d.ts +3 -0
  44. package/dist/types/chrome-cookies.d.ts +44 -0
  45. package/dist/types/cloudflare-search.d.ts +4 -0
  46. package/dist/types/content-find.d.ts +10 -0
  47. package/dist/types/crawl4ai.d.ts +8 -0
  48. package/dist/types/credential-source.d.ts +29 -0
  49. package/dist/types/curator-page.d.ts +5 -0
  50. package/dist/types/curator-run.d.ts +10 -0
  51. package/dist/types/curator-server.d.ts +72 -0
  52. package/dist/types/custom-search.d.ts +22 -0
  53. package/dist/types/data-uri-sanitize.d.ts +20 -0
  54. package/dist/types/datalab-pdf-extract.d.ts +59 -0
  55. package/dist/types/declared-web-links.d.ts +7 -0
  56. package/dist/types/deepseek.d.ts +13 -0
  57. package/dist/types/degoog.d.ts +3 -0
  58. package/dist/types/domain-filter-normalization.d.ts +9 -0
  59. package/dist/types/duckduckgo-rate-limit.d.ts +52 -0
  60. package/dist/types/duckduckgo.d.ts +6 -0
  61. package/dist/types/endpoint-pdf-extract.d.ts +22 -0
  62. package/dist/types/exa.d.ts +17 -0
  63. package/dist/types/extract.d.ts +70 -0
  64. package/dist/types/feature-config.d.ts +2 -0
  65. package/dist/types/fetch-params.d.ts +39 -0
  66. package/dist/types/field-extract.d.ts +37 -0
  67. package/dist/types/firecrawl.d.ts +18 -0
  68. package/dist/types/gemini-adc.d.ts +9 -0
  69. package/dist/types/gemini-api.d.ts +37 -0
  70. package/dist/types/gemini-pdf-extract.d.ts +8 -0
  71. package/dist/types/gemini-search.d.ts +76 -0
  72. package/dist/types/gemini-url-context.d.ts +3 -0
  73. package/dist/types/gemini-web-config.d.ts +25 -0
  74. package/dist/types/gemini-web.d.ts +31 -0
  75. package/dist/types/github-api.d.ts +6 -0
  76. package/dist/types/github-extract.d.ts +19 -0
  77. package/dist/types/github-issue-pr.d.ts +28 -0
  78. package/dist/types/index.d.ts +53 -0
  79. package/dist/types/jina-search.d.ts +7 -0
  80. package/dist/types/kagi.d.ts +14 -0
  81. package/dist/types/keenable.d.ts +3 -0
  82. package/dist/types/kimi-search.d.ts +4 -0
  83. package/dist/types/linkup.d.ts +5 -0
  84. package/dist/types/mcp-cli.d.ts +2 -0
  85. package/dist/types/mcp-server.d.ts +10 -0
  86. package/dist/types/mcp-tool-definitions.d.ts +16 -0
  87. package/dist/types/mistral-search.d.ts +3 -0
  88. package/dist/types/ninerouter.d.ts +3 -0
  89. package/dist/types/offtopic-judge.d.ts +26 -0
  90. package/dist/types/ollama.d.ts +14 -0
  91. package/dist/types/openai-search.d.ts +23 -0
  92. package/dist/types/page-query.d.ts +22 -0
  93. package/dist/types/parallel-mcp.d.ts +10 -0
  94. package/dist/types/parallel.d.ts +13 -0
  95. package/dist/types/pdf-extract.d.ts +44 -0
  96. package/dist/types/perplexity.d.ts +26 -0
  97. package/dist/types/pi-mcp.d.ts +56 -0
  98. package/dist/types/pi-session-results.d.ts +8 -0
  99. package/dist/types/querit.d.ts +9 -0
  100. package/dist/types/query-rewrite.d.ts +2 -0
  101. package/dist/types/render-search-error.d.ts +56 -0
  102. package/dist/types/retrieval-only.d.ts +78 -0
  103. package/dist/types/rsc-extract.d.ts +11 -0
  104. package/dist/types/search-answer-formatting.d.ts +7 -0
  105. package/dist/types/search-result-count-normalization.d.ts +1 -0
  106. package/dist/types/searchinfinity.d.ts +7 -0
  107. package/dist/types/searxng.d.ts +3 -0
  108. package/dist/types/source-check.d.ts +102 -0
  109. package/dist/types/ssrf-protection.d.ts +66 -0
  110. package/dist/types/storage.d.ts +69 -0
  111. package/dist/types/summary-model-scope.d.ts +33 -0
  112. package/dist/types/summary-review.d.ts +30 -0
  113. package/dist/types/tabstack.d.ts +5 -0
  114. package/dist/types/tavily.d.ts +7 -0
  115. package/dist/types/tinyfish.d.ts +10 -0
  116. package/dist/types/tool-activation.d.ts +7 -0
  117. package/dist/types/tool-arguments.d.ts +1 -0
  118. package/dist/types/upgrade-notice.d.ts +6 -0
  119. package/dist/types/utils.d.ts +55 -0
  120. package/dist/types/valyu.d.ts +5 -0
  121. package/dist/types/video-extract.d.ts +15 -0
  122. package/dist/types/web-tool-contract.d.ts +98 -0
  123. package/dist/types/web-tool-core.d.ts +227 -0
  124. package/dist/types/xai-search.d.ts +12 -0
  125. package/dist/types/you.d.ts +3 -0
  126. package/dist/types/youtube-extract.d.ts +29 -0
  127. package/dist/types/zai.d.ts +3 -0
  128. package/docs/pi-mcp.md +41 -0
  129. package/domain-filter-normalization.ts +44 -0
  130. package/duckduckgo-rate-limit.ts +205 -0
  131. package/duckduckgo.ts +123 -0
  132. package/endpoint-pdf-extract.ts +225 -0
  133. package/exa.ts +620 -0
  134. package/extract.ts +1721 -0
  135. package/feature-config.ts +29 -0
  136. package/fetch-params.ts +147 -0
  137. package/field-extract.ts +347 -0
  138. package/firecrawl.ts +476 -0
  139. package/gemini-adc.ts +345 -0
  140. package/gemini-api.ts +368 -0
  141. package/gemini-pdf-extract.ts +108 -0
  142. package/gemini-search.ts +1162 -0
  143. package/gemini-url-context.ts +128 -0
  144. package/gemini-web-config.ts +131 -0
  145. package/gemini-web.ts +527 -0
  146. package/github-api.ts +197 -0
  147. package/github-extract.ts +1064 -0
  148. package/github-issue-pr.ts +717 -0
  149. package/index.ts +2819 -0
  150. package/jina-search.ts +275 -0
  151. package/kagi.ts +257 -0
  152. package/keenable.ts +222 -0
  153. package/kimi-search.ts +209 -0
  154. package/linkup.ts +170 -0
  155. package/mcp-cli.ts +40 -0
  156. package/mcp-server.ts +84 -0
  157. package/mcp-tool-definitions.ts +143 -0
  158. package/mistral-search.ts +268 -0
  159. package/ninerouter.ts +92 -0
  160. package/offtopic-judge.ts +72 -0
  161. package/ollama.ts +237 -0
  162. package/openai-search.ts +855 -0
  163. package/package.json +108 -4
  164. package/page-query.ts +185 -0
  165. package/parallel-mcp.ts +255 -0
  166. package/parallel.ts +373 -0
  167. package/pdf-extract.ts +447 -0
  168. package/perplexity.ts +245 -0
  169. package/pi-mcp.ts +139 -0
  170. package/pi-session-results.ts +40 -0
  171. package/pi-web-fetch-demo.mp4 +0 -0
  172. package/promise-try.d.ts +7 -0
  173. package/querit.ts +394 -0
  174. package/query-rewrite.ts +84 -0
  175. package/render-search-error.ts +170 -0
  176. package/retrieval-only.ts +102 -0
  177. package/rsc-extract.ts +338 -0
  178. package/search-answer-formatting.ts +11 -0
  179. package/search-result-count-normalization.ts +4 -0
  180. package/searchinfinity.ts +246 -0
  181. package/searxng.ts +236 -0
  182. package/source-check.ts +269 -0
  183. package/ssrf-protection.ts +602 -0
  184. package/storage.ts +547 -0
  185. package/summary-model-scope.ts +72 -0
  186. package/summary-review.ts +476 -0
  187. package/tabstack.ts +289 -0
  188. package/tavily.ts +257 -0
  189. package/tinyfish.ts +373 -0
  190. package/tool-activation.ts +169 -0
  191. package/tool-arguments.ts +23 -0
  192. package/upgrade-notice.ts +47 -0
  193. package/utils.ts +693 -0
  194. package/valyu.ts +177 -0
  195. package/video-extract.ts +398 -0
  196. package/web-tool-contract.ts +93 -0
  197. package/web-tool-core.ts +1810 -0
  198. package/xai-search.ts +443 -0
  199. package/you.ts +165 -0
  200. package/youtube-extract.ts +336 -0
  201. package/zai.ts +161 -0
package/firecrawl.ts ADDED
@@ -0,0 +1,476 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { activityMonitor } from "./activity.ts";
3
+ import { normalizeDomain } from "./domain-filter-normalization.ts";
4
+ import { redactCredential, resolveCredential } from "./credential-source.ts";
5
+ import type { ExtractedContent, ExtractOptions } from "./extract.ts";
6
+ import type { SearchOptions, SearchResponse } from "./perplexity.ts";
7
+ import { formatSearchResultsAsAnswer } from "./search-answer-formatting.ts";
8
+ import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
9
+ import { loadSsrfConfig, validateRemoteUrl, type Lookup } from "./ssrf-protection.ts";
10
+ import { getWebSearchConfigPath, isLoopbackHostname } from "./utils.ts";
11
+
12
+ const CONFIG_PATH = getWebSearchConfigPath();
13
+ const DEFAULT_API_VERSION = "v2";
14
+ const EXTRACT_TIMEOUT_MS = 60_000;
15
+ const SEARCH_TIMEOUT_MS = 60_000;
16
+ const DEFAULT_MAX_REDIRECTS = 5;
17
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
18
+ const SUPPORTED_API_VERSIONS = ["v1", "v2"] as const;
19
+ type FirecrawlApiVersion = (typeof SUPPORTED_API_VERSIONS)[number];
20
+
21
+ export interface FirecrawlSsrfOptions {
22
+ allowRanges: string[];
23
+ trustEnvProxy: boolean;
24
+ }
25
+
26
+ export interface FirecrawlExtractOptions extends Pick<ExtractOptions, "timeoutMs" | "lookup"> {
27
+ ssrf?: FirecrawlSsrfOptions;
28
+ }
29
+
30
+ interface FirecrawlSearchOptions extends SearchOptions, Pick<ExtractOptions, "timeoutMs" | "lookup"> {
31
+ includeContent?: boolean;
32
+ ssrf?: FirecrawlSsrfOptions;
33
+ }
34
+
35
+ interface FirecrawlConfig {
36
+ firecrawlBaseUrl?: unknown;
37
+ firecrawlApiKey?: unknown;
38
+ firecrawlApiVersion?: unknown;
39
+ firecrawlFreshScrape?: unknown;
40
+ firecrawlPdfMaxPages?: unknown;
41
+ }
42
+
43
+ interface FirecrawlPageMetadata {
44
+ numPages?: unknown;
45
+ totalPages?: unknown;
46
+ }
47
+
48
+ interface FirecrawlScrapeData {
49
+ title?: unknown;
50
+ markdown?: unknown;
51
+ metadata?: { title?: unknown; statusCode?: unknown; url?: unknown } & FirecrawlPageMetadata;
52
+ }
53
+
54
+ interface FirecrawlSearchItem {
55
+ title?: unknown;
56
+ description?: unknown;
57
+ snippet?: unknown;
58
+ url?: unknown;
59
+ markdown?: unknown;
60
+ metadata?: FirecrawlPageMetadata & {
61
+ title?: unknown;
62
+ description?: unknown;
63
+ sourceURL?: unknown;
64
+ url?: unknown;
65
+ };
66
+ }
67
+
68
+ interface DomainFilters {
69
+ include: string[];
70
+ exclude: string[];
71
+ }
72
+
73
+ let cachedConfig: FirecrawlConfig | null = null;
74
+
75
+ function loadConfig(): FirecrawlConfig {
76
+ if (cachedConfig) return cachedConfig;
77
+ if (!existsSync(CONFIG_PATH)) {
78
+ cachedConfig = {};
79
+ return cachedConfig;
80
+ }
81
+ const raw = readFileSync(CONFIG_PATH, "utf8");
82
+ let parsed: unknown;
83
+ try {
84
+ parsed = JSON.parse(raw);
85
+ } catch (err) {
86
+ const message = err instanceof Error ? err.message : String(err);
87
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
88
+ }
89
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
90
+ throw new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);
91
+ }
92
+ cachedConfig = parsed as FirecrawlConfig;
93
+ return cachedConfig;
94
+ }
95
+
96
+ export function clearFirecrawlConfigCache(): void {
97
+ cachedConfig = null;
98
+ }
99
+
100
+ function normalizeBaseUrl(value: unknown): string | null {
101
+ if (typeof value !== "string") return null;
102
+ const trimmed = value.trim();
103
+ if (!trimmed) return null;
104
+ let parsed: URL;
105
+ try {
106
+ parsed = new URL(trimmed);
107
+ } catch {
108
+ throw new Error(`Invalid Firecrawl base URL in ${CONFIG_PATH}: expected an HTTP or HTTPS URL`);
109
+ }
110
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
111
+ throw new Error(`Invalid Firecrawl base URL in ${CONFIG_PATH}: expected an HTTP or HTTPS URL`);
112
+ }
113
+ if (parsed.username || parsed.password) {
114
+ throw new Error(`Invalid Firecrawl base URL in ${CONFIG_PATH}: URL credentials are not allowed`);
115
+ }
116
+ parsed.pathname = parsed.pathname.replace(/\/+$/, "");
117
+ parsed.search = "";
118
+ parsed.hash = "";
119
+ return parsed.toString().replace(/\/+$/, "");
120
+ }
121
+
122
+ function getBaseUrl(): string | null {
123
+ return normalizeBaseUrl(process.env.FIRECRAWL_BASE_URL) ?? normalizeBaseUrl(loadConfig().firecrawlBaseUrl);
124
+ }
125
+
126
+ function requireBaseUrl(): string {
127
+ const baseUrl = getBaseUrl();
128
+ if (!baseUrl) {
129
+ throw new Error(
130
+ "Firecrawl base URL not configured. Either:\n" +
131
+ ` 1. Set firecrawlBaseUrl in ${CONFIG_PATH}\n` +
132
+ " 2. Set FIRECRAWL_BASE_URL environment variable",
133
+ );
134
+ }
135
+ return baseUrl;
136
+ }
137
+
138
+ function getApiVersion(): FirecrawlApiVersion {
139
+ const environmentValue = typeof process.env.FIRECRAWL_API_VERSION === "string"
140
+ ? process.env.FIRECRAWL_API_VERSION.trim()
141
+ : "";
142
+ const raw = environmentValue || loadConfig().firecrawlApiVersion;
143
+ if (raw === undefined || raw === null) return DEFAULT_API_VERSION;
144
+ if (typeof raw !== "string") {
145
+ throw new Error(`firecrawlApiVersion in ${CONFIG_PATH} must be a string ("v1" or "v2")`);
146
+ }
147
+ const normalized = raw.trim().toLowerCase();
148
+ if (!normalized) return DEFAULT_API_VERSION;
149
+ if (!SUPPORTED_API_VERSIONS.includes(normalized as FirecrawlApiVersion)) {
150
+ throw new Error(`Unsupported Firecrawl API version "${raw}". Supported versions: ${SUPPORTED_API_VERSIONS.join(", ")}`);
151
+ }
152
+ return normalized as FirecrawlApiVersion;
153
+ }
154
+
155
+ function allowFreshScrape(): boolean {
156
+ const environmentValue = process.env.FIRECRAWL_FRESH_SCRAPE;
157
+ if (environmentValue !== undefined) return environmentValue === "1" || environmentValue.toLowerCase() === "true";
158
+ const configured = loadConfig().firecrawlFreshScrape;
159
+ if (configured === undefined || configured === null) return false;
160
+ if (typeof configured !== "boolean") throw new Error(`firecrawlFreshScrape in ${CONFIG_PATH} must be a boolean`);
161
+ return configured;
162
+ }
163
+
164
+ function pdfParserOptions(): { parsers?: Array<{ type: "pdf"; maxPages: number }> } {
165
+ const configured = loadConfig().firecrawlPdfMaxPages;
166
+ if (configured === undefined || configured === null) return {};
167
+ if (typeof configured !== "number" || !Number.isInteger(configured) || configured < 1) {
168
+ throw new Error(`firecrawlPdfMaxPages in ${CONFIG_PATH} must be a positive integer`);
169
+ }
170
+ if (getApiVersion() === "v1") {
171
+ throw new Error(
172
+ `firecrawlPdfMaxPages in ${CONFIG_PATH} requires Firecrawl API v2; v1 has no PDF page cap. ` +
173
+ "Use firecrawlApiVersion \"v2\" or remove firecrawlPdfMaxPages",
174
+ );
175
+ }
176
+ return { parsers: [{ type: "pdf", maxPages: configured }] };
177
+ }
178
+
179
+ function withPdfTruncationNotice(content: string, metadata: FirecrawlPageMetadata | undefined): string {
180
+ const parsed = metadata?.numPages;
181
+ const total = metadata?.totalPages;
182
+ if (typeof parsed !== "number" || typeof total !== "number" || parsed >= total) return content;
183
+ return `${content}\n\n---\n\n*[Truncated: Only first ${parsed} of ${total} PDF pages parsed by Firecrawl]*`;
184
+ }
185
+
186
+ async function getApiKey(signal?: AbortSignal): Promise<string | null> {
187
+ const configKey = loadConfig().firecrawlApiKey;
188
+ return resolveCredential({
189
+ provider: "Firecrawl",
190
+ configuredValue: configKey,
191
+ environmentValue: process.env.FIRECRAWL_API_KEY,
192
+ signal,
193
+ });
194
+ }
195
+
196
+ function requestSignal(timeoutMs: number, signal?: AbortSignal): AbortSignal {
197
+ const timeout = AbortSignal.timeout(timeoutMs);
198
+ return signal ? AbortSignal.any([timeout, signal]) : timeout;
199
+ }
200
+
201
+ function errorMessage(err: unknown): string {
202
+ return err instanceof Error ? err.message : String(err);
203
+ }
204
+
205
+ function isAbortError(err: unknown): boolean {
206
+ return errorMessage(err).toLowerCase().includes("abort");
207
+ }
208
+
209
+ function ssrfOptions(options?: FirecrawlExtractOptions | FirecrawlSearchOptions): { lookup?: Lookup; allowRanges: string[]; trustEnvProxy: boolean } {
210
+ const config = loadSsrfConfig();
211
+ return {
212
+ allowRanges: options?.ssrf?.allowRanges ?? config.allowRanges,
213
+ trustEnvProxy: options?.ssrf?.trustEnvProxy ?? config.trustEnvProxy,
214
+ ...(options?.lookup ? { lookup: options.lookup } : {}),
215
+ };
216
+ }
217
+
218
+ function firecrawlApiSsrfOptions(
219
+ options: FirecrawlExtractOptions | FirecrawlSearchOptions | undefined,
220
+ allowLoopback: boolean,
221
+ ): ReturnType<typeof ssrfOptions> & { allowLoopback: boolean } {
222
+ return { ...ssrfOptions(options), allowLoopback };
223
+ }
224
+
225
+ function withoutSensitiveHeaders(headers: Record<string, string>): Record<string, string> {
226
+ const next = { ...headers };
227
+ delete next.Authorization;
228
+ delete next.authorization;
229
+ delete next.Cookie;
230
+ delete next.cookie;
231
+ delete next["X-API-Key"];
232
+ delete next["x-api-key"];
233
+ return next;
234
+ }
235
+
236
+ async function fetchFirecrawlApi(
237
+ url: string,
238
+ init: { method: string; headers: Record<string, string>; body: string; signal: AbortSignal },
239
+ options: FirecrawlExtractOptions | FirecrawlSearchOptions | undefined,
240
+ ): Promise<Response> {
241
+ const allowLoopback = isLoopbackHostname(new URL(url).hostname);
242
+ let current = await validateRemoteUrl(url, firecrawlApiSsrfOptions(options, allowLoopback));
243
+ let headers = init.headers;
244
+ for (let redirects = 0; redirects <= DEFAULT_MAX_REDIRECTS; redirects++) {
245
+ const response = await fetch(current, { ...init, headers, redirect: "manual" });
246
+ if (!REDIRECT_STATUSES.has(response.status)) return response;
247
+
248
+ const location = response.headers.get("location");
249
+ if (!location) return response;
250
+ if (redirects === DEFAULT_MAX_REDIRECTS) throw new Error(`Too many redirects fetching ${current.toString()}`);
251
+
252
+ const next = await validateRemoteUrl(new URL(location, current), firecrawlApiSsrfOptions(options, allowLoopback));
253
+ if (next.origin !== current.origin) headers = withoutSensitiveHeaders(headers);
254
+ current = next;
255
+ }
256
+ throw new Error(`Too many redirects fetching ${current.toString()}`);
257
+ }
258
+
259
+ function scrapeBody(url: string): Record<string, unknown> {
260
+ return {
261
+ url,
262
+ formats: ["markdown"],
263
+ onlyMainContent: true,
264
+ ...(allowFreshScrape() ? {} : { lockdown: true }),
265
+ ...pdfParserOptions(),
266
+ };
267
+ }
268
+
269
+ function parseDomainFilter(domainFilter: string[] | undefined): DomainFilters {
270
+ const filters: DomainFilters = { include: [], exclude: [] };
271
+ for (const raw of domainFilter ?? []) {
272
+ const domain = normalizeDomain(raw);
273
+ if (!domain) continue;
274
+ const target = raw.trim().startsWith("-") ? filters.exclude : filters.include;
275
+ if (!target.includes(domain)) target.push(domain);
276
+ }
277
+ return filters;
278
+ }
279
+
280
+ function passesDomainFilters(url: string, filters: DomainFilters): boolean {
281
+ if (filters.include.length === 0 && filters.exclude.length === 0) return true;
282
+ let hostname: string;
283
+ try {
284
+ hostname = new URL(url).hostname.toLowerCase();
285
+ } catch {
286
+ return false;
287
+ }
288
+ const matches = (domain: string) => hostname === domain || hostname.endsWith(`.${domain}`);
289
+ if (filters.exclude.some(matches)) return false;
290
+ return filters.include.length === 0 || filters.include.some(matches);
291
+ }
292
+
293
+ function mapRecencyFilter(value: SearchOptions["recencyFilter"]): string | undefined {
294
+ switch (value) {
295
+ case "day": return "qdr:d";
296
+ case "week": return "qdr:w";
297
+ case "month": return "qdr:m";
298
+ case "year": return "qdr:y";
299
+ default: return undefined;
300
+ }
301
+ }
302
+
303
+ function searchBody(query: string, options: FirecrawlSearchOptions, numResults: number, filters: DomainFilters): Record<string, unknown> {
304
+ const parserOptions = pdfParserOptions();
305
+ return {
306
+ query,
307
+ limit: numResults,
308
+ sources: ["web"],
309
+ ...(filters.include.length > 0 ? { includeDomains: filters.include } : {}),
310
+ ...(filters.include.length === 0 && filters.exclude.length > 0 ? { excludeDomains: filters.exclude } : {}),
311
+ ...(mapRecencyFilter(options.recencyFilter) ? { tbs: mapRecencyFilter(options.recencyFilter) } : {}),
312
+ ...(options.includeContent ? {
313
+ scrapeOptions: {
314
+ formats: ["markdown"],
315
+ onlyMainContent: true,
316
+ ...(allowFreshScrape() ? {} : { lockdown: true }),
317
+ ...parserOptions,
318
+ },
319
+ } : {}),
320
+ };
321
+ }
322
+
323
+ function firstString(...values: unknown[]): string | null {
324
+ for (const value of values) {
325
+ if (typeof value === "string" && value.trim()) return value.trim();
326
+ }
327
+ return null;
328
+ }
329
+
330
+ function mapSearchResults(data: unknown, numResults: number, filters: DomainFilters): {
331
+ results: SearchResponse["results"];
332
+ inlineContent: ExtractedContent[];
333
+ } {
334
+ const web = Array.isArray(data)
335
+ ? data
336
+ : data && typeof data === "object" ? (data as Record<string, unknown>).web : undefined;
337
+ if (!Array.isArray(web)) throw new Error("Firecrawl search returned an unexpected web result shape");
338
+ const results: SearchResponse["results"] = [];
339
+ const inlineContent: ExtractedContent[] = [];
340
+ const seen = new Set<string>();
341
+ for (const rawItem of web) {
342
+ if (!rawItem || typeof rawItem !== "object" || Array.isArray(rawItem)) continue;
343
+ const item = rawItem as FirecrawlSearchItem;
344
+ const url = firstString(item.url, item.metadata?.sourceURL, item.metadata?.url);
345
+ if (!url || seen.has(url) || !passesDomainFilters(url, filters)) continue;
346
+ seen.add(url);
347
+ const title = firstString(item.title, item.metadata?.title) ?? url;
348
+ const snippet = firstString(item.description, item.snippet, item.metadata?.description) ?? "";
349
+ results.push({ title, url, snippet });
350
+ const markdown = firstString(item.markdown);
351
+ if (markdown) inlineContent.push({ url, title, content: withPdfTruncationNotice(markdown, item.metadata), error: null });
352
+ if (results.length >= numResults) break;
353
+ }
354
+ return { results, inlineContent };
355
+ }
356
+
357
+ async function firecrawlFetch(
358
+ endpoint: string,
359
+ body: Record<string, unknown>,
360
+ signal: AbortSignal | undefined,
361
+ options: FirecrawlExtractOptions | FirecrawlSearchOptions | undefined,
362
+ label = endpoint,
363
+ activity: { type: "api"; query: string } | { type: "fetch"; url: string } | undefined = undefined,
364
+ ): Promise<Record<string, unknown>> {
365
+ const baseUrl = requireBaseUrl();
366
+ const version = getApiVersion();
367
+ const apiKey = await getApiKey(signal);
368
+ const headers: Record<string, string> = { "Content-Type": "application/json" };
369
+ if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
370
+ const requestUrl = `${baseUrl}/${version}/${endpoint}`;
371
+ const activityId = activityMonitor.logStart(activity ?? { type: "fetch", url: requestUrl });
372
+ try {
373
+ const response = await fetchFirecrawlApi(requestUrl, {
374
+ method: "POST",
375
+ headers,
376
+ body: JSON.stringify(body),
377
+ signal: requestSignal(options?.timeoutMs ?? EXTRACT_TIMEOUT_MS, signal),
378
+ }, options);
379
+ if (!response.ok) {
380
+ const text = await response.text().catch(() => "");
381
+ throw new Error(`Firecrawl ${label} error ${response.status}: ${redactCredential(text.slice(0, 300), apiKey)}`);
382
+ }
383
+ let data: unknown;
384
+ try {
385
+ data = await response.json();
386
+ } catch (err) {
387
+ throw new Error(`Firecrawl ${label} returned invalid JSON: ${errorMessage(err)}`);
388
+ }
389
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
390
+ throw new Error(`Firecrawl ${label} returned an unexpected response shape`);
391
+ }
392
+ const envelope = data as Record<string, unknown>;
393
+ if (envelope.success === false) {
394
+ const reason = typeof envelope.error === "string" && envelope.error.trim() ? envelope.error : "unknown error";
395
+ throw new Error(`Firecrawl ${label} unsuccessful: ${redactCredential(reason, apiKey)}`);
396
+ }
397
+ if (envelope.success !== true) {
398
+ throw new Error(`Firecrawl ${label} returned an unexpected response shape`);
399
+ }
400
+ activityMonitor.logComplete(activityId, response.status);
401
+ return envelope;
402
+ } catch (err) {
403
+ if (isAbortError(err)) activityMonitor.logComplete(activityId, 0);
404
+ else activityMonitor.logError(activityId, errorMessage(err));
405
+ throw err;
406
+ }
407
+ }
408
+
409
+ export function isFirecrawlAvailable(): boolean {
410
+ return getBaseUrl() !== null;
411
+ }
412
+
413
+ export async function searchWithFirecrawl(query: string, options: FirecrawlSearchOptions = {}): Promise<SearchResponse> {
414
+ requireBaseUrl();
415
+ const numResults = normalizeSearchResultCount(options.numResults);
416
+ const filters = parseDomainFilter(options.domainFilter);
417
+ const envelope = await firecrawlFetch(
418
+ "search",
419
+ searchBody(query, options, numResults, filters),
420
+ options.signal,
421
+ { ...options, timeoutMs: options.timeoutMs ?? SEARCH_TIMEOUT_MS },
422
+ "search",
423
+ { type: "api", query },
424
+ );
425
+ const mapped = mapSearchResults(envelope.data, numResults, filters);
426
+ const response: SearchResponse = { answer: formatSearchResultsAsAnswer(mapped.results), results: mapped.results };
427
+ if (options.includeContent && mapped.inlineContent.length > 0) response.inlineContent = mapped.inlineContent;
428
+ return response;
429
+ }
430
+
431
+ export async function extractWithFirecrawl(
432
+ url: string,
433
+ signal?: AbortSignal,
434
+ options?: FirecrawlExtractOptions,
435
+ ): Promise<ExtractedContent | null> {
436
+ requireBaseUrl();
437
+ await validateRemoteUrl(url, ssrfOptions(options));
438
+ const envelope = await firecrawlFetch("scrape", scrapeBody(url), signal, options);
439
+ const data = envelope.data;
440
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
441
+ throw new Error("Firecrawl scrape returned an unexpected data shape");
442
+ }
443
+ const scrape = data as FirecrawlScrapeData;
444
+ if (typeof scrape.markdown !== "string") {
445
+ throw new Error("Firecrawl scrape returned markdown in an unexpected shape");
446
+ }
447
+ // Firecrawl scrapes the origin's own error page with success: true, so its status decides whether this is a read.
448
+ const originStatus = scrape.metadata?.statusCode;
449
+ if (typeof originStatus === "number" && originStatus >= 400) {
450
+ // No URL in the message: extract.ts treats any error mentioning "abort" as a cancel.
451
+ throw new Error(`Firecrawl got HTTP ${originStatus} from the site`);
452
+ }
453
+ const content = scrape.markdown.trim();
454
+ if (!content) return null;
455
+ const metadataTitle = scrape.metadata?.title;
456
+ const title = typeof metadataTitle === "string" && metadataTitle.trim()
457
+ ? metadataTitle.trim()
458
+ : typeof scrape.title === "string" ? scrape.title.trim() : "";
459
+ const finalUrl = redirectedUrl(url, scrape.metadata?.url);
460
+ const page = withPdfTruncationNotice(content, scrape.metadata);
461
+ return { url, title, content: finalUrl ? `*[Redirected: Firecrawl read this page from ${finalUrl}]*\n\n${page}` : page, error: null };
462
+ }
463
+
464
+ function redirectedUrl(requested: string, final: unknown): string | null {
465
+ if (typeof final !== "string") return null;
466
+ try {
467
+ const requestedUrl = new URL(requested);
468
+ const finalUrl = new URL(final);
469
+ // Firecrawl drops the fragment and may normalize the URL; only a different page counts as a redirect.
470
+ requestedUrl.hash = "";
471
+ finalUrl.hash = "";
472
+ return requestedUrl.href === finalUrl.href ? null : finalUrl.href;
473
+ } catch {
474
+ return null;
475
+ }
476
+ }