@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/parallel.ts ADDED
@@ -0,0 +1,373 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { activityMonitor } from "./activity.ts";
3
+ import { normalizeDomain } from "./domain-filter-normalization.ts";
4
+ import type { ExtractedContent, ExtractOptions } from "./extract.ts";
5
+ import type { SearchOptions, SearchResponse } from "./perplexity.ts";
6
+ import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
7
+ import { fetchWithCredentialRedirects, getWebSearchConfigPath, resolveProviderApiUrl } from "./utils.ts";
8
+
9
+ const PARALLEL_API_BASE_URL = "https://api.parallel.ai";
10
+ const CONFIG_PATH = getWebSearchConfigPath();
11
+ const MIN_PARALLEL_API_KEY_LENGTH = 8;
12
+ const MIN_USEFUL_CONTENT = 500;
13
+ const SEARCH_TIMEOUT_MS = 60_000;
14
+
15
+ const PLACEHOLDER_API_KEY_DENYLIST = new Set([
16
+ "replace_with_your_parallel_api_key",
17
+ "parallel_api_key",
18
+ "your-key",
19
+ "your-key-here",
20
+ "your-api-key-here",
21
+ "dummy",
22
+ "placeholder",
23
+ "changeme",
24
+ "insert-your-key",
25
+ "insert-your-key-here",
26
+ "api-key",
27
+ "xxx",
28
+ ]);
29
+
30
+ interface WebSearchConfig {
31
+ parallelApiKey?: unknown;
32
+ parallelBaseUrl?: unknown;
33
+ }
34
+
35
+ interface V1WebSearchResult {
36
+ url: string;
37
+ title?: string | null;
38
+ publish_date?: string | null;
39
+ excerpts?: string[];
40
+ }
41
+
42
+ interface V1ExtractResult {
43
+ url: string;
44
+ title?: string | null;
45
+ publish_date?: string | null;
46
+ excerpts?: string[];
47
+ full_content?: string | null;
48
+ }
49
+
50
+ interface ParallelSearchOptions extends SearchOptions {
51
+ includeContent?: boolean;
52
+ objective?: string;
53
+ }
54
+
55
+ let cachedConfig: WebSearchConfig | null = null;
56
+
57
+ function loadConfig(): WebSearchConfig {
58
+ if (cachedConfig) return cachedConfig;
59
+ if (!existsSync(CONFIG_PATH)) {
60
+ cachedConfig = {};
61
+ return cachedConfig;
62
+ }
63
+
64
+ const raw = readFileSync(CONFIG_PATH, "utf-8");
65
+ try {
66
+ cachedConfig = JSON.parse(raw) as WebSearchConfig;
67
+ return cachedConfig;
68
+ } catch (err) {
69
+ const message = err instanceof Error ? err.message : String(err);
70
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
71
+ }
72
+ }
73
+
74
+ export function clearParallelConfigCache(): void {
75
+ cachedConfig = null;
76
+ }
77
+
78
+ function normalizeApiKey(value: unknown): string | null {
79
+ if (typeof value !== "string") return null;
80
+ const normalized = value.trim();
81
+ return normalized.length > 0 ? normalized : null;
82
+ }
83
+
84
+ function isPlaceholderApiKey(key: string): boolean {
85
+ const normalized = key.trim();
86
+ return normalized.length < MIN_PARALLEL_API_KEY_LENGTH || PLACEHOLDER_API_KEY_DENYLIST.has(normalized.toLowerCase());
87
+ }
88
+
89
+ export async function resolveParallelApiKey(signal?: AbortSignal): Promise<string | null> {
90
+ const configKey = normalizeApiKey(loadConfig().parallelApiKey);
91
+ if (configKey?.startsWith("$") || configKey?.startsWith("!")) {
92
+ const resolved = await resolveCredential({
93
+ provider: "Parallel",
94
+ configuredValue: configKey,
95
+ environmentValue: process.env.PARALLEL_API_KEY,
96
+ signal,
97
+ });
98
+ return resolved && !isPlaceholderApiKey(resolved) ? resolved : null;
99
+ }
100
+
101
+ const envKey = normalizeApiKey(process.env.PARALLEL_API_KEY);
102
+ if (envKey && !isPlaceholderApiKey(envKey)) return envKey;
103
+ if (configKey && !isPlaceholderApiKey(configKey)) return configKey;
104
+ return null;
105
+ }
106
+
107
+ function hasConfiguredApiKey(): boolean {
108
+ const configKey = normalizeApiKey(loadConfig().parallelApiKey);
109
+ if (configKey?.startsWith("$") || configKey?.startsWith("!")) {
110
+ return hasCredentialSource({
111
+ provider: "Parallel",
112
+ configuredValue: configKey,
113
+ environmentValue: process.env.PARALLEL_API_KEY,
114
+ });
115
+ }
116
+ const envKey = normalizeApiKey(process.env.PARALLEL_API_KEY);
117
+ return (envKey !== null && !isPlaceholderApiKey(envKey)) || (configKey !== null && !isPlaceholderApiKey(configKey));
118
+ }
119
+
120
+ async function getApiKey(signal?: AbortSignal): Promise<string> {
121
+ const key = await resolveParallelApiKey(signal);
122
+ if (!key) {
123
+ throw new Error(
124
+ "Parallel API key not found. Either:\n" +
125
+ ` 1. Create ${CONFIG_PATH} with { "parallelApiKey": "your-key" }\n` +
126
+ " 2. Set PARALLEL_API_KEY environment variable\n" +
127
+ "Get a key at https://platform.parallel.ai",
128
+ );
129
+ }
130
+ return key;
131
+ }
132
+
133
+ export function hasParallelApiKey(): boolean {
134
+ return hasConfiguredApiKey();
135
+ }
136
+
137
+ export function isParallelAvailable(): boolean {
138
+ return hasParallelApiKey();
139
+ }
140
+
141
+ function requestSignal(signal?: AbortSignal): AbortSignal {
142
+ const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
143
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
144
+ }
145
+
146
+ function errorMessage(err: unknown): string {
147
+ return err instanceof Error ? err.message : String(err);
148
+ }
149
+
150
+ function activityContext(
151
+ url: string,
152
+ body: Record<string, unknown>,
153
+ ): { type: "api" | "fetch"; query?: string; url?: string } {
154
+ if (typeof body.objective === "string" && body.objective.trim().length > 0) {
155
+ return { type: "api", query: body.objective };
156
+ }
157
+
158
+ const searchQueries = body.search_queries;
159
+ if (Array.isArray(searchQueries) && typeof searchQueries[0] === "string") {
160
+ return { type: "api", query: searchQueries[0] };
161
+ }
162
+
163
+ const urls = body.urls;
164
+ if (Array.isArray(urls) && typeof urls[0] === "string") {
165
+ return { type: "fetch", url: urls[0] };
166
+ }
167
+
168
+ return url.includes("/search") ? { type: "api", query: "Parallel search" } : { type: "fetch", url };
169
+ }
170
+
171
+ function recencyToAfterDate(filter: string): string {
172
+ const now = new Date();
173
+ const offsets: Record<string, number> = { day: 1, week: 7, month: 30, year: 365 };
174
+ const days = offsets[filter] ?? 0;
175
+ return new Date(now.getTime() - days * 86_400_000).toISOString().slice(0, 10);
176
+ }
177
+
178
+ function mapDomainFilter(domainFilter: string[] | undefined): { include_domains?: string[]; exclude_domains?: string[] } {
179
+ if (!domainFilter?.length) return {};
180
+ const include_domains: string[] = [];
181
+ const exclude_domains: string[] = [];
182
+ for (const raw of domainFilter) {
183
+ const domain = normalizeDomain(raw);
184
+ if (!domain) continue;
185
+ const target = raw.trim().startsWith("-") ? exclude_domains : include_domains;
186
+ if (!target.includes(domain)) target.push(domain);
187
+ }
188
+ return {
189
+ ...(include_domains.length ? { include_domains } : {}),
190
+ ...(exclude_domains.length ? { exclude_domains } : {}),
191
+ };
192
+ }
193
+
194
+ function buildSearchRequestBody(query: string, options: ParallelSearchOptions = {}): Record<string, unknown> {
195
+ const numResults = Math.max(1, Math.min(Math.floor(options.numResults ?? 5), 20));
196
+ const sourcePolicy = {
197
+ ...mapDomainFilter(options.domainFilter),
198
+ ...(options.recencyFilter ? { after_date: recencyToAfterDate(options.recencyFilter) } : {}),
199
+ };
200
+ return {
201
+ objective: options.objective?.trim() || query,
202
+ search_queries: [query],
203
+ advanced_settings: {
204
+ max_results: numResults,
205
+ ...(Object.keys(sourcePolicy).length > 0 ? { source_policy: sourcePolicy } : {}),
206
+ },
207
+ };
208
+ }
209
+
210
+ function normalizeExcerpts(value: unknown): string[] {
211
+ if (!Array.isArray(value)) return [];
212
+ return value.filter((item): item is string => typeof item === "string" && item.trim().length > 0);
213
+ }
214
+
215
+ function mapSearchResults(results: V1WebSearchResult[] | undefined): SearchResponse["results"] {
216
+ if (!Array.isArray(results)) return [];
217
+ const mapped: SearchResponse["results"] = [];
218
+ for (let i = 0; i < results.length; i++) {
219
+ const item = results[i];
220
+ if (!item?.url) continue;
221
+ const excerpts = normalizeExcerpts(item.excerpts);
222
+ mapped.push({
223
+ title: item.title || `Source ${i + 1}`,
224
+ url: item.url,
225
+ snippet: excerpts.length > 0 ? excerpts[0].replace(/\s+/g, " ").trim().slice(0, 200) : "",
226
+ });
227
+ }
228
+ return mapped;
229
+ }
230
+
231
+ function buildAnswerFromExcerpts(results: V1WebSearchResult[] | undefined): string {
232
+ if (!Array.isArray(results)) return "";
233
+ const parts: string[] = [];
234
+ for (let i = 0; i < results.length; i++) {
235
+ const item = results[i];
236
+ if (!item?.url) continue;
237
+ const excerpts = normalizeExcerpts(item.excerpts);
238
+ if (excerpts.length === 0) continue;
239
+ parts.push(`${excerpts.join(" ")}\nSource: ${item.title || `Source ${i + 1}`} (${item.url})`);
240
+ }
241
+ return parts.join("\n\n");
242
+ }
243
+
244
+ function mapInlineContent(results: V1WebSearchResult[] | undefined): ExtractedContent[] {
245
+ if (!Array.isArray(results)) return [];
246
+ return results.flatMap((result) => {
247
+ if (!result?.url) return [];
248
+ const excerpts = normalizeExcerpts(result.excerpts);
249
+ if (excerpts.length === 0) return [];
250
+ return [{ url: result.url, title: result.title || "", content: excerpts.join("\n\n"), error: null }];
251
+ });
252
+ }
253
+
254
+ function resolveExtractContent(result: V1ExtractResult): string {
255
+ const fullContent = typeof result.full_content === "string" ? result.full_content.trim() : "";
256
+ return fullContent.length > 0 ? fullContent : normalizeExcerpts(result.excerpts).join("\n\n");
257
+ }
258
+
259
+ function mapExtractResult(result: V1ExtractResult | undefined | null): ExtractedContent | null {
260
+ if (!result?.url) return null;
261
+ const content = resolveExtractContent(result);
262
+ if (content.length < MIN_USEFUL_CONTENT) return null;
263
+ return {
264
+ url: result.url,
265
+ title: typeof result.title === "string" ? result.title.trim() : "",
266
+ content,
267
+ error: null,
268
+ };
269
+ }
270
+
271
+ function buildExtractRequestBody(url: string, options: ExtractOptions = {}, fullContent = false): Record<string, unknown> {
272
+ const body: Record<string, unknown> = { urls: [url] };
273
+ const prompt = options.prompt?.trim();
274
+ if (prompt) body.objective = prompt;
275
+ if (fullContent) body.advanced_settings = { full_content: true };
276
+ return body;
277
+ }
278
+
279
+ function findExtractResult(results: V1ExtractResult[] | undefined, url: string): V1ExtractResult | undefined {
280
+ if (!Array.isArray(results)) return undefined;
281
+ return results.find(item => item?.url === url) ?? results[0];
282
+ }
283
+
284
+ function hasExtractUrlError(errors: unknown, url: string): boolean {
285
+ if (!Array.isArray(errors)) return false;
286
+ return errors.some((entry) => {
287
+ if (typeof entry === "string") return entry === url;
288
+ return typeof entry === "object" && entry !== null && (entry as { url?: unknown }).url === url;
289
+ });
290
+ }
291
+
292
+ async function fetchAndMapExtractResult(
293
+ url: string,
294
+ body: Record<string, unknown>,
295
+ signal?: AbortSignal,
296
+ ): Promise<{ mapped: ExtractedContent | null; result: V1ExtractResult | undefined }> {
297
+ const data = await parallelFetch(resolveProviderApiUrl("parallel", `${PARALLEL_API_BASE_URL}/v1/extract`, loadConfig().parallelBaseUrl), body, signal);
298
+ if (hasExtractUrlError(data.errors, url)) return { mapped: null, result: undefined };
299
+ const result = findExtractResult(data.results as V1ExtractResult[] | undefined, url);
300
+ return { mapped: mapExtractResult(result), result };
301
+ }
302
+
303
+ export async function searchWithParallel(query: string, options: ParallelSearchOptions = {}): Promise<SearchResponse> {
304
+ const data = await parallelFetch(resolveProviderApiUrl("parallel", `${PARALLEL_API_BASE_URL}/v1/search`, loadConfig().parallelBaseUrl), buildSearchRequestBody(query, options), options.signal);
305
+ const results = data.results as V1WebSearchResult[] | undefined;
306
+ const response: SearchResponse = {
307
+ answer: buildAnswerFromExcerpts(results),
308
+ results: mapSearchResults(results),
309
+ };
310
+ if (options.includeContent) {
311
+ const inlineContent = mapInlineContent(results);
312
+ if (inlineContent.length > 0) response.inlineContent = inlineContent;
313
+ }
314
+ return response;
315
+ }
316
+
317
+ export async function extractWithParallel(
318
+ url: string,
319
+ signal?: AbortSignal,
320
+ options: ExtractOptions = {},
321
+ ): Promise<ExtractedContent | null> {
322
+ const initial = await fetchAndMapExtractResult(url, buildExtractRequestBody(url, options), signal);
323
+ if (initial.mapped) return initial.mapped;
324
+ if (!initial.result || resolveExtractContent(initial.result).length >= MIN_USEFUL_CONTENT) return null;
325
+
326
+ const retry = await fetchAndMapExtractResult(url, buildExtractRequestBody(url, options, true), signal);
327
+ return retry.mapped;
328
+ }
329
+
330
+ async function parallelFetch(
331
+ url: string,
332
+ body: Record<string, unknown>,
333
+ signal?: AbortSignal,
334
+ ): Promise<Record<string, unknown>> {
335
+ const apiKey = await getApiKey(signal);
336
+ const activityId = activityMonitor.logStart(activityContext(url, body));
337
+ let response: Response;
338
+ try {
339
+ response = await fetchWithCredentialRedirects(url, {
340
+ method: "POST",
341
+ headers: {
342
+ "x-api-key": apiKey,
343
+ "Content-Type": "application/json",
344
+ },
345
+ body: JSON.stringify(body),
346
+ signal: requestSignal(signal),
347
+ }, ["x-api-key"]);
348
+ } catch (err) {
349
+ const message = errorMessage(err);
350
+ const redactedMessage = redactCredential(message, apiKey);
351
+ if (redactedMessage.toLowerCase().includes("abort")) activityMonitor.logComplete(activityId, 0);
352
+ else activityMonitor.logError(activityId, redactedMessage);
353
+ if (redactedMessage === message) throw err;
354
+ const redactedError = new Error(redactedMessage);
355
+ if (err instanceof Error) redactedError.name = err.name;
356
+ throw redactedError;
357
+ }
358
+
359
+ if (!response.ok) {
360
+ activityMonitor.logComplete(activityId, response.status);
361
+ const errorText = redactCredential(await response.text(), apiKey);
362
+ throw new Error(`Parallel API error ${response.status}: ${errorText.slice(0, 300)}`);
363
+ }
364
+
365
+ try {
366
+ const data = await response.json() as Record<string, unknown>;
367
+ activityMonitor.logComplete(activityId, response.status);
368
+ return data;
369
+ } catch (err) {
370
+ activityMonitor.logComplete(activityId, response.status);
371
+ throw new Error(`Parallel API returned invalid JSON: ${errorMessage(err)}`);
372
+ }
373
+ }