@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/exa.ts ADDED
@@ -0,0 +1,620 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { activityMonitor } from "./activity.ts";
3
+ import type { ExtractedContent, ExtractOptions } from "./extract.ts";
4
+ import type { SearchOptions, SearchResponse } from "./perplexity.ts";
5
+ import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
6
+ import { loadFetchContentDomainPolicy, loadSsrfConfig, validateRemoteUrl } from "./ssrf-protection.ts";
7
+ import { fetchWithCredentialRedirects, getWebSearchConfigPath, isRecord, resolveApiBaseUrl } from "./utils.ts";
8
+
9
+ const EXA_API_BASE_URL = "https://api.exa.ai";
10
+ const EXA_MCP_URL = "https://mcp.exa.ai/mcp";
11
+ const CONFIG_PATH = getWebSearchConfigPath();
12
+ const EXA_MCP_ADVANCED_TOOL = "web_search_advanced_exa";
13
+ const EXA_MCP_BASIC_TOOL = "web_search_exa";
14
+ const CONTENTS_TIMEOUT_MS = 60_000;
15
+ const MAX_EXA_OBJECTIVE_LENGTH = 4096;
16
+
17
+ interface WebSearchConfig {
18
+ exaApiKey?: unknown;
19
+ exaBaseUrl?: unknown;
20
+ }
21
+
22
+ interface ExaSearchResponse {
23
+ results?: Array<{
24
+ title?: string;
25
+ url?: string;
26
+ publishedDate?: string;
27
+ author?: string;
28
+ text?: string;
29
+ highlights?: unknown;
30
+ highlightScores?: number[];
31
+ entities?: unknown;
32
+ }>;
33
+ }
34
+
35
+ interface ExaMcpRpcResponse {
36
+ result?: {
37
+ _meta?: Record<string, unknown>;
38
+ content?: Array<{ type?: string; text?: string }>;
39
+ isError?: boolean;
40
+ };
41
+ error?: {
42
+ code?: number;
43
+ message?: string;
44
+ };
45
+ }
46
+
47
+ export interface ExaSearchOptions extends SearchOptions {
48
+ includeContent?: boolean;
49
+ objective?: string;
50
+ /** Restrict results to an Exa content category (e.g. "publication", "news", "company"). */
51
+ category?: string;
52
+ }
53
+
54
+ type McpParsedResult = { title: string; url: string; content: string; publishedDate?: string; author?: string };
55
+
56
+ const MAX_LISTED_AUTHORS = 3;
57
+
58
+ let cachedConfig: WebSearchConfig | null = null;
59
+
60
+ function loadConfig(): WebSearchConfig {
61
+ if (cachedConfig) return cachedConfig;
62
+ if (!existsSync(CONFIG_PATH)) {
63
+ cachedConfig = {};
64
+ return cachedConfig;
65
+ }
66
+
67
+ const raw = readFileSync(CONFIG_PATH, "utf-8");
68
+ try {
69
+ cachedConfig = JSON.parse(raw) as WebSearchConfig;
70
+ return cachedConfig;
71
+ } catch (err) {
72
+ const message = err instanceof Error ? err.message : String(err);
73
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
74
+ }
75
+ }
76
+
77
+ async function getApiKey(signal?: AbortSignal): Promise<string | null> {
78
+ return resolveCredential({
79
+ provider: "Exa",
80
+ configuredValue: loadConfig().exaApiKey,
81
+ environmentValue: process.env.EXA_API_KEY,
82
+ signal,
83
+ });
84
+ }
85
+
86
+ function getApiBaseUrl(): string {
87
+ return resolveApiBaseUrl({
88
+ configKey: "exaBaseUrl",
89
+ configuredValue: loadConfig().exaBaseUrl,
90
+ defaultValue: EXA_API_BASE_URL,
91
+ environmentKey: "EXA_BASE_URL",
92
+ environmentValue: process.env.EXA_BASE_URL,
93
+ });
94
+ }
95
+
96
+ function exaApiHeaders(apiKey: string): Record<string, string> {
97
+ return {
98
+ "x-api-key": apiKey,
99
+ "Content-Type": "application/json",
100
+ "x-exa-integration": "pi-web-access",
101
+ };
102
+ }
103
+
104
+ function requestSignal(signal?: AbortSignal): AbortSignal {
105
+ const timeout = AbortSignal.timeout(60000);
106
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
107
+ }
108
+
109
+ function recencyToStartDate(filter: string): string {
110
+ const now = new Date();
111
+ const offsets: Record<string, number> = {
112
+ day: 1,
113
+ week: 7,
114
+ month: 30,
115
+ year: 365,
116
+ };
117
+ const days = offsets[filter] ?? 0;
118
+ return new Date(now.getTime() - days * 86400000).toISOString();
119
+ }
120
+
121
+ function mapDomainFilter(domainFilter: string[] | undefined): { includeDomains?: string[]; excludeDomains?: string[] } {
122
+ if (!domainFilter?.length) return {};
123
+ const includeDomains = domainFilter
124
+ .filter(d => !d.startsWith("-") && d.trim().length > 0)
125
+ .map(d => d.trim());
126
+ const excludeDomains = domainFilter
127
+ .filter(d => d.startsWith("-"))
128
+ .map(d => d.slice(1).trim())
129
+ .filter(Boolean);
130
+ return {
131
+ ...(includeDomains.length ? { includeDomains } : {}),
132
+ ...(excludeDomains.length ? { excludeDomains } : {}),
133
+ };
134
+ }
135
+
136
+ function exaSearchArgs(query: string, options: ExaSearchOptions): Record<string, unknown> {
137
+ const startDate = options.recencyFilter ? recencyToStartDate(options.recencyFilter) : null;
138
+ return {
139
+ query,
140
+ type: "auto",
141
+ numResults: options.numResults ?? 5,
142
+ ...mapDomainFilter(options.domainFilter),
143
+ ...(options.category ? { category: options.category } : {}),
144
+ ...(startDate ? { startPublishedDate: startDate } : {}),
145
+ };
146
+ }
147
+
148
+ function normalizeHighlights(value: unknown): string[] {
149
+ if (!Array.isArray(value)) return [];
150
+ return value.filter((item): item is string => typeof item === "string" && item.trim().length > 0);
151
+ }
152
+
153
+ function fallbackSourceLabel(url: string | undefined, index: number): string {
154
+ try {
155
+ const hostname = url ? new URL(url).hostname : "";
156
+ if (hostname) return hostname;
157
+ } catch {
158
+ // Invalid URLs use the generic label.
159
+ }
160
+ return `Source ${index + 1}`;
161
+ }
162
+
163
+ function nonEmptyString(value: unknown): string | null {
164
+ return typeof value === "string" && value.trim().length > 0 && value.trim() !== "N/A" ? value.trim() : null;
165
+ }
166
+
167
+ function publicationProperties(entities: unknown): Record<string, unknown> | null {
168
+ const entity: unknown = Array.isArray(entities) ? entities.find(item => isRecord(item) && item.type === "publication") : undefined;
169
+ return isRecord(entity) && isRecord(entity.properties) ? entity.properties : null;
170
+ }
171
+
172
+ function listAuthors(names: string[]): string | null {
173
+ if (names.length === 0) return null;
174
+ const listed = names.slice(0, MAX_LISTED_AUTHORS).join(", ");
175
+ return names.length > MAX_LISTED_AUTHORS ? `${listed} et al.` : listed;
176
+ }
177
+
178
+ /** One line of the date, authors and, for Exa's `publication` category, the citation count and DOI. */
179
+ function formatResultMetadata(item: { publishedDate?: string; author?: string; entities?: unknown }): string {
180
+ const paper = publicationProperties(item.entities);
181
+ const parts: string[] = [];
182
+ const date = (nonEmptyString(item.publishedDate) ?? nonEmptyString(paper?.date))?.slice(0, 10)
183
+ ?? (typeof paper?.year === "number" ? String(paper.year) : null);
184
+ if (date) parts.push(`Published: ${date}`);
185
+ const paperAuthors = Array.isArray(paper?.authors) ? paper.authors.flatMap(author => nonEmptyString(isRecord(author) ? author.name : null) ?? []) : [];
186
+ // Exa's top-level `author` joins every paper author with ", ".
187
+ const authors = listAuthors(paperAuthors) ?? listAuthors(nonEmptyString(item.author)?.split(", ").map(name => name.trim()).filter(Boolean) ?? []);
188
+ if (authors) parts.push(`Authors: ${authors}`);
189
+ if (typeof paper?.citationCount === "number") parts.push(`Citations: ${paper.citationCount}`);
190
+ const doi = nonEmptyString(paper?.doi);
191
+ if (doi) parts.push(`DOI: ${doi}`);
192
+ return parts.length > 0 ? `\n${parts.join(" | ")}` : "";
193
+ }
194
+
195
+ function buildAnswerFromSearchResults(results: ExaSearchResponse["results"]): string {
196
+ if (!results?.length) return "";
197
+ const parts: string[] = [];
198
+ for (let i = 0; i < results.length; i++) {
199
+ const item = results[i];
200
+ if (!item?.url) continue;
201
+ const highlights = normalizeHighlights(item.highlights);
202
+ const content = highlights.length > 0
203
+ ? highlights.join(" ")
204
+ : typeof item.text === "string" ? item.text.trim().slice(0, 1000) : "";
205
+ if (!content) continue;
206
+ const sourceTitle = item.title || fallbackSourceLabel(item.url, i);
207
+ parts.push(`${content}\nSource: ${sourceTitle} (${item.url})${formatResultMetadata(item)}`);
208
+ }
209
+ return parts.join("\n\n");
210
+ }
211
+
212
+ function mapResults(results: ExaSearchResponse["results"]): SearchResponse["results"] {
213
+ if (!Array.isArray(results)) return [];
214
+ const mapped: SearchResponse["results"] = [];
215
+ for (let i = 0; i < results.length; i++) {
216
+ const item = results[i];
217
+ if (!item?.url) continue;
218
+ mapped.push({
219
+ title: item.title || fallbackSourceLabel(item.url, i),
220
+ url: item.url,
221
+ snippet: "",
222
+ });
223
+ }
224
+ return mapped;
225
+ }
226
+
227
+ function mapInlineContent(results: ExaSearchResponse["results"]): ExtractedContent[] {
228
+ if (!results?.length) return [];
229
+ return results.flatMap((r, i) => r?.url && typeof r.text === "string" && r.text.length > 0
230
+ ? [{ url: r.url, title: r.title || fallbackSourceLabel(r.url, i), content: r.text, error: null }]
231
+ : []);
232
+ }
233
+
234
+ function toSearchResponse(
235
+ answer: string,
236
+ results: SearchResponse["results"],
237
+ inlineContent: ExtractedContent[] | null,
238
+ ): SearchResponse {
239
+ const response: SearchResponse = { answer, results };
240
+ if (inlineContent?.length) response.inlineContent = inlineContent;
241
+ return response;
242
+ }
243
+
244
+ export async function callExaMcp(
245
+ toolName: string,
246
+ args: Record<string, unknown>,
247
+ signal?: AbortSignal,
248
+ ): Promise<string> {
249
+ const response = await fetch(`${EXA_MCP_URL}?tools=${toolName}`, {
250
+ method: "POST",
251
+ headers: {
252
+ "Content-Type": "application/json",
253
+ "Accept": "application/json, text/event-stream",
254
+ "x-exa-source": "pi-web-access",
255
+ },
256
+ body: JSON.stringify({
257
+ jsonrpc: "2.0",
258
+ id: 1,
259
+ method: "tools/call",
260
+ params: {
261
+ name: toolName,
262
+ arguments: args,
263
+ },
264
+ }),
265
+ signal: requestSignal(signal),
266
+ });
267
+
268
+ if (!response.ok) {
269
+ const errorText = await response.text();
270
+ if (response.status === 429) {
271
+ throw new Error(
272
+ `Exa MCP rate limit reached (429). Add "exaApiKey" to ${CONFIG_PATH} for unthrottled Exa search: ${errorText.slice(0, 200)}`,
273
+ );
274
+ }
275
+ throw new Error(`Exa MCP error ${response.status}: ${errorText.slice(0, 300)}`);
276
+ }
277
+
278
+ const body = await response.text();
279
+ const dataLines = body.split("\n").filter(line => line.startsWith("data:"));
280
+
281
+ let parsed: ExaMcpRpcResponse | null = null;
282
+ for (const line of dataLines) {
283
+ const payload = line.slice(5).trim();
284
+ if (!payload) continue;
285
+ try {
286
+ const candidate = JSON.parse(payload) as ExaMcpRpcResponse;
287
+ if (candidate?.result || candidate?.error) {
288
+ parsed = candidate;
289
+ break;
290
+ }
291
+ } catch {
292
+ }
293
+ }
294
+
295
+ if (!parsed) {
296
+ try {
297
+ const candidate = JSON.parse(body) as ExaMcpRpcResponse;
298
+ if (candidate?.result || candidate?.error) {
299
+ parsed = candidate;
300
+ }
301
+ } catch {
302
+ }
303
+ }
304
+
305
+ if (!parsed) {
306
+ throw new Error("Exa MCP returned an empty response");
307
+ }
308
+
309
+ if (parsed.error) {
310
+ const code = typeof parsed.error.code === "number" ? ` ${parsed.error.code}` : "";
311
+ const message = parsed.error.message || "Unknown error";
312
+ throw new Error(`Exa MCP error${code}: ${message}`);
313
+ }
314
+
315
+ // The free endpoint answers a rate limit with HTTP 200 and this flag, not a 429.
316
+ if (parsed.result?._meta?.["ai.exa/rateLimited"] === true) {
317
+ throw new Error(
318
+ `Exa's free MCP search hit its rate limit. Add "exaApiKey" to ${CONFIG_PATH} or set EXA_API_KEY for unthrottled Exa search.`,
319
+ );
320
+ }
321
+
322
+ if (parsed.result?.isError) {
323
+ const message = parsed.result.content
324
+ ?.find(item => item.type === "text" && typeof item.text === "string")
325
+ ?.text?.trim();
326
+ throw new Error(message || "Exa MCP returned an error");
327
+ }
328
+
329
+ const text = parsed.result?.content
330
+ ?.find(item => item.type === "text" && typeof item.text === "string" && item.text.trim().length > 0)
331
+ ?.text;
332
+
333
+ if (!text) {
334
+ throw new Error("Exa MCP returned empty content");
335
+ }
336
+
337
+ return text;
338
+ }
339
+
340
+ function parseMcpResults(text: string): McpParsedResult[] | null {
341
+ const blocks = text.split(/(?=^Title: )/m).filter(block => block.trim().length > 0);
342
+ const parsed = blocks.map(block => {
343
+ const title = block.match(/^Title: (.+)/m)?.[1]?.trim() ?? "";
344
+ const url = block.match(/^URL: (.+)/m)?.[1]?.trim() ?? "";
345
+ let content = "";
346
+ let contentStart = block.length;
347
+ const textStart = block.indexOf("\nText: ");
348
+ if (textStart >= 0) {
349
+ content = block.slice(textStart + 7).trim();
350
+ contentStart = textStart;
351
+ } else {
352
+ const hlMatch = block.match(/\nHighlights:\s*\n/);
353
+ if (hlMatch?.index != null) {
354
+ content = block.slice(hlMatch.index + hlMatch[0].length).trim();
355
+ contentStart = hlMatch.index;
356
+ }
357
+ }
358
+ content = content.replace(/\n---\s*$/, "").trim();
359
+ // Read metadata from the header only, so a quoted "Author:" line in the page text is not taken as the source's.
360
+ const header = block.slice(0, contentStart);
361
+ const publishedDate = header.match(/^Published: (.+)/m)?.[1]?.trim();
362
+ const author = header.match(/^Author: (.+)/m)?.[1]?.trim();
363
+ return { title, url, content, publishedDate, author };
364
+ }).filter(result => result.url.length > 0);
365
+ return parsed.length > 0 ? parsed : null;
366
+ }
367
+
368
+ function buildAnswerFromMcpResults(results: McpParsedResult[]): string {
369
+ if (results.length === 0) return "";
370
+ const parts: string[] = [];
371
+ for (let i = 0; i < results.length; i++) {
372
+ const result = results[i];
373
+ const snippet = result.content.replace(/\s+/g, " ").trim().slice(0, 500);
374
+ if (!snippet) continue;
375
+ const sourceTitle = result.title || fallbackSourceLabel(result.url, i);
376
+ parts.push(`${snippet}\nSource: ${sourceTitle} (${result.url})${formatResultMetadata(result)}`);
377
+ }
378
+ return parts.join("\n\n");
379
+ }
380
+
381
+ function mapMcpInlineContent(results: McpParsedResult[]): ExtractedContent[] {
382
+ return results.flatMap((result, i) => result.content.length > 0
383
+ ? [{ url: result.url, title: result.title || fallbackSourceLabel(result.url, i), content: result.content, error: null }]
384
+ : []);
385
+ }
386
+
387
+ function buildMcpQuery(query: string, options: ExaSearchOptions): string {
388
+ const parts = [query];
389
+ if (options.domainFilter?.length) {
390
+ for (const d of options.domainFilter) {
391
+ parts.push(d.startsWith("-") ? `-site:${d.slice(1)}` : `site:${d}`);
392
+ }
393
+ }
394
+ if (options.recencyFilter) {
395
+ const now = new Date();
396
+ switch (options.recencyFilter) {
397
+ case "day": parts.push("past 24 hours"); break;
398
+ case "week": parts.push("past week"); break;
399
+ case "month": parts.push(`${now.toLocaleString("en", { month: "long" })} ${now.getFullYear()}`); break;
400
+ case "year": parts.push(String(now.getFullYear())); break;
401
+ }
402
+ }
403
+ if (options.category) parts.push(options.category);
404
+ return parts.join(" ");
405
+ }
406
+
407
+ function isAbortMessage(message: string): boolean {
408
+ return message.toLowerCase().includes("abort");
409
+ }
410
+
411
+ function parseJsonMcpResults(text: string): ExaSearchResponse["results"] | null {
412
+ try {
413
+ const results = (JSON.parse(text) as ExaSearchResponse).results;
414
+ return Array.isArray(results) ? results : null;
415
+ } catch {
416
+ return null;
417
+ }
418
+ }
419
+
420
+ /**
421
+ * Normalizes one Exa MCP search tool's payload. `web_search_advanced_exa`
422
+ * returns the raw Exa search JSON; `web_search_exa` returns a formatted text block.
423
+ */
424
+ function toMcpSearchResponse(text: string, options: ExaSearchOptions): SearchResponse {
425
+ const jsonResults = parseJsonMcpResults(text);
426
+ if (jsonResults) {
427
+ return toSearchResponse(
428
+ buildAnswerFromSearchResults(jsonResults),
429
+ mapResults(jsonResults),
430
+ options.includeContent ? mapInlineContent(jsonResults) : null,
431
+ );
432
+ }
433
+
434
+ const textResults = parseMcpResults(text);
435
+ if (!textResults) {
436
+ throw new Error(`Exa MCP returned no parseable results: ${text.trim().slice(0, 200)}`);
437
+ }
438
+
439
+ return toSearchResponse(
440
+ buildAnswerFromMcpResults(textResults),
441
+ mapResults(textResults),
442
+ options.includeContent ? mapMcpInlineContent(textResults) : null,
443
+ );
444
+ }
445
+
446
+ /** Filtered searches need the advanced tool, which not every deployment exposes. */
447
+ async function searchWithFilteredExaMcp(
448
+ query: string,
449
+ options: ExaSearchOptions,
450
+ basicArgs: Record<string, unknown>,
451
+ ): Promise<SearchResponse> {
452
+ let text: string;
453
+ try {
454
+ text = await callExaMcp(EXA_MCP_ADVANCED_TOOL, {
455
+ ...exaSearchArgs(query, options),
456
+ enableHighlights: true,
457
+ textMaxCharacters: options.includeContent ? 50000 : 3000,
458
+ }, options.signal);
459
+ } catch (err) {
460
+ if (isAbortMessage(err instanceof Error ? err.message : String(err))) throw err;
461
+ // The basic tool ignores every argument except query/numResults, so the
462
+ // filters degrade into the query text.
463
+ return toMcpSearchResponse(await callExaMcp(EXA_MCP_BASIC_TOOL, basicArgs, options.signal), options);
464
+ }
465
+ // An unreadable advanced reply is not retried on the basic tool, which would drop the filters.
466
+ return toMcpSearchResponse(text, options);
467
+ }
468
+
469
+ async function searchWithExaMcp(query: string, options: ExaSearchOptions = {}): Promise<SearchResponse> {
470
+ const activityId = activityMonitor.logStart({ type: "api", query });
471
+ const basicArgs = { query: buildMcpQuery(query, options), numResults: options.numResults ?? 5 };
472
+ const filtered = !!options.includeContent || !!options.recencyFilter || !!options.domainFilter?.length || !!options.category;
473
+
474
+ try {
475
+ const response = filtered
476
+ ? await searchWithFilteredExaMcp(query, options, basicArgs)
477
+ : toMcpSearchResponse(await callExaMcp(EXA_MCP_BASIC_TOOL, basicArgs, options.signal), options);
478
+ activityMonitor.logComplete(activityId, 200);
479
+ return response;
480
+ } catch (err) {
481
+ const message = err instanceof Error ? err.message : String(err);
482
+ if (isAbortMessage(message)) {
483
+ activityMonitor.logComplete(activityId, 0);
484
+ } else {
485
+ activityMonitor.logError(activityId, message);
486
+ }
487
+ throw err;
488
+ }
489
+ }
490
+
491
+ export function isExaAvailable(): boolean {
492
+ return true;
493
+ }
494
+
495
+ export function hasExaApiKey(): boolean {
496
+ return hasCredentialSource({
497
+ provider: "Exa",
498
+ configuredValue: loadConfig().exaApiKey,
499
+ environmentValue: process.env.EXA_API_KEY,
500
+ });
501
+ }
502
+
503
+ export async function searchWithExa(query: string, options: ExaSearchOptions = {}): Promise<SearchResponse> {
504
+ const apiKey = await getApiKey(options.signal);
505
+ if (!apiKey) {
506
+ return searchWithExaMcp(query, options);
507
+ }
508
+ if (options.objective !== undefined && [...options.objective].length > MAX_EXA_OBJECTIVE_LENGTH) {
509
+ throw new Error(`Exa objective must be ${MAX_EXA_OBJECTIVE_LENGTH} characters or fewer`);
510
+ }
511
+
512
+ const apiBaseUrl = getApiBaseUrl();
513
+ const activityId = activityMonitor.logStart({ type: "api", query });
514
+
515
+ try {
516
+ const response = await fetchWithCredentialRedirects(`${apiBaseUrl}/search`, {
517
+ method: "POST",
518
+ headers: exaApiHeaders(apiKey),
519
+ body: JSON.stringify({
520
+ ...exaSearchArgs(query, options),
521
+ ...(options.objective !== undefined ? { objective: options.objective } : {}),
522
+ contents: options.includeContent
523
+ ? { text: true, highlights: true }
524
+ : { highlights: true },
525
+ }),
526
+ signal: requestSignal(options.signal),
527
+ }, ["x-api-key"]);
528
+
529
+ if (!response.ok) {
530
+ const errorText = redactCredential(await response.text(), apiKey);
531
+ throw new Error(`Exa API error ${response.status}: ${errorText.slice(0, 300)}`);
532
+ }
533
+
534
+ const data = await response.json() as ExaSearchResponse;
535
+ activityMonitor.logComplete(activityId, response.status);
536
+
537
+ return toSearchResponse(
538
+ buildAnswerFromSearchResults(data.results),
539
+ mapResults(data.results),
540
+ options.includeContent ? mapInlineContent(data.results) : null,
541
+ );
542
+ } catch (err) {
543
+ const message = err instanceof Error ? err.message : String(err);
544
+ const redactedMessage = redactCredential(message, apiKey);
545
+ if (isAbortMessage(redactedMessage)) {
546
+ activityMonitor.logComplete(activityId, 0);
547
+ } else {
548
+ activityMonitor.logError(activityId, redactedMessage);
549
+ }
550
+ if (redactedMessage === message) throw err;
551
+ throw new Error(redactedMessage);
552
+ }
553
+ }
554
+
555
+ /**
556
+ * Read one page through Exa's /contents endpoint with the configured Exa key.
557
+ * Opt-in via `fetchRouting.providers`; returns null when Exa has no text for the page.
558
+ */
559
+ export async function extractWithExa(
560
+ url: string,
561
+ signal?: AbortSignal,
562
+ options: Pick<ExtractOptions, "timeoutMs" | "lookup"> = {},
563
+ ): Promise<ExtractedContent | null> {
564
+ const apiKey = await getApiKey(signal);
565
+ if (!apiKey) throw new Error("Exa fetch requires exaApiKey or EXA_API_KEY");
566
+ const activityId = activityMonitor.logStart({ type: "fetch", url });
567
+ const timeoutMs = options.timeoutMs ?? CONTENTS_TIMEOUT_MS;
568
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
569
+ try {
570
+ const ssrf = loadSsrfConfig();
571
+ await validateRemoteUrl(url, {
572
+ allowRanges: ssrf.allowRanges,
573
+ trustEnvProxy: ssrf.trustEnvProxy,
574
+ domainPolicy: loadFetchContentDomainPolicy(),
575
+ ...(options.lookup ? { lookup: options.lookup } : {}),
576
+ });
577
+ const response = await fetchWithCredentialRedirects(`${getApiBaseUrl()}/contents`, {
578
+ method: "POST",
579
+ headers: exaApiHeaders(apiKey),
580
+ body: JSON.stringify({ urls: [url], text: true }),
581
+ signal: signal ? AbortSignal.any([timeoutSignal, signal]) : timeoutSignal,
582
+ }, ["x-api-key"]);
583
+ if (!response.ok) {
584
+ throw new Error(`Exa contents error ${response.status}: ${redactCredential(await response.text(), apiKey).slice(0, 300)}`);
585
+ }
586
+ const data: unknown = await response.json();
587
+ if (!isRecord(data) || !Array.isArray(data.results)) {
588
+ throw new Error("Exa contents returned an unexpected response shape");
589
+ }
590
+ const failed = Array.isArray(data.statuses)
591
+ ? data.statuses.find((status): status is Record<string, unknown> => isRecord(status) && status.status === "error")
592
+ : undefined;
593
+ if (failed) {
594
+ const detail = isRecord(failed.error) ? failed.error : {};
595
+ const tag = typeof detail.tag === "string" ? detail.tag : "unknown error";
596
+ const httpStatus = typeof detail.httpStatusCode === "number" ? ` (HTTP ${detail.httpStatusCode})` : "";
597
+ throw new Error(`Exa could not read ${url}: ${tag}${httpStatus}`);
598
+ }
599
+ const page: unknown = data.results[0];
600
+ const content = isRecord(page) && typeof page.text === "string" ? page.text.trim() : "";
601
+ activityMonitor.logComplete(activityId, response.status);
602
+ if (!content) return null;
603
+ return {
604
+ url,
605
+ title: isRecord(page) && typeof page.title === "string" ? page.title.trim() : "",
606
+ content,
607
+ error: null,
608
+ };
609
+ } catch (err) {
610
+ if (signal?.aborted) {
611
+ activityMonitor.logComplete(activityId, 0);
612
+ throw new Error("Aborted");
613
+ }
614
+ const message = timeoutSignal.aborted || (err instanceof Error && err.name === "TimeoutError")
615
+ ? `Exa contents request timed out after ${Math.round(timeoutMs / 1000)}s`
616
+ : redactCredential(err instanceof Error ? err.message : String(err), apiKey);
617
+ activityMonitor.logError(activityId, message);
618
+ throw new Error(message);
619
+ }
620
+ }