@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/pdf-extract.ts ADDED
@@ -0,0 +1,447 @@
1
+ /**
2
+ * PDF Content Extractor
3
+ *
4
+ * Converts PDFs to Markdown. The `auto` provider chain runs Datalab
5
+ * (deterministic, layout-aware) first, then Gemini API, with unpdf as the
6
+ * deterministic local fallback; the chain can also be pinned with
7
+ * `pdf.provider`.
8
+ */
9
+
10
+ import { existsSync, readFileSync } from "node:fs";
11
+ import { writeFile, mkdir } from "node:fs/promises";
12
+ import { join, basename } from "node:path";
13
+ import { tmpdir } from "node:os";
14
+ import { CredentialResolutionError } from "./credential-source.ts";
15
+ import {
16
+ DATALAB_MODE_VALUES,
17
+ DEFAULT_DATALAB_TIMEOUT_MS,
18
+ isDatalabApiAvailable,
19
+ normalizeDatalabMode,
20
+ extractPDFViaDatalab,
21
+ type DatalabMode,
22
+ } from "./datalab-pdf-extract.ts";
23
+ import { isGeminiApiAvailable } from "./gemini-api.ts";
24
+ import {
25
+ extractPDFViaEndpoint,
26
+ isEndpointApiAvailable,
27
+ } from "./endpoint-pdf-extract.ts";
28
+ import { extractPDFViaGemini } from "./gemini-pdf-extract.ts";
29
+ import { getWebSearchConfigPath } from "./utils.ts";
30
+ import { getRetrievalOnlyPolicy, PDF_PROVIDER_KINDS, retrievalOnlyError } from "./retrieval-only.ts";
31
+
32
+ export interface PDFExtractResult {
33
+ title: string;
34
+ /** The same Markdown written to outputPath. */
35
+ content: string;
36
+ outputPath: string;
37
+ }
38
+
39
+ export interface PDFExtractOptions {
40
+ maxPages?: number;
41
+ outputDir?: string;
42
+ filename?: string;
43
+ signal?: AbortSignal;
44
+ geminiTimeoutMs?: number;
45
+ }
46
+
47
+ export type PDFProvider = "auto" | "endpoint" | "gemini" | "datalab" | "unpdf";
48
+
49
+ export const PDF_PROVIDER_VALUES = new Set<PDFProvider>([
50
+ "auto",
51
+ "endpoint",
52
+ "gemini",
53
+ "datalab",
54
+ "unpdf",
55
+ ]);
56
+
57
+ export interface PDFConfig {
58
+ enabled: boolean;
59
+ maxSizeMB: number;
60
+ maxPages: number;
61
+ provider: PDFProvider;
62
+ datalabMode: DatalabMode;
63
+ datalabTimeoutMs: number;
64
+ }
65
+
66
+ export const DEFAULT_PDF_MAX_SIZE_MB = 20;
67
+ export const MAX_PDF_MAX_SIZE_MB = 50;
68
+ export const MAX_DATALAB_TIMEOUT_MS = 300_000;
69
+ const DEFAULT_MAX_PAGES = 100;
70
+ const DEFAULT_OUTPUT_DIR = join(tmpdir(), "pi-web-pdf");
71
+ const CONFIG_PATH = getWebSearchConfigPath();
72
+ const PAGE_MARKER_PATTERN = /^<!-- Page (\d+) -->$/gm;
73
+
74
+ export function loadPDFConfig(): PDFConfig {
75
+ if (!existsSync(CONFIG_PATH)) {
76
+ return {
77
+ enabled: true,
78
+ maxSizeMB: DEFAULT_PDF_MAX_SIZE_MB,
79
+ maxPages: DEFAULT_MAX_PAGES,
80
+ provider: "auto",
81
+ datalabMode: normalizeDatalabMode(process.env.DATALAB_MODE),
82
+ datalabTimeoutMs: DEFAULT_DATALAB_TIMEOUT_MS,
83
+ };
84
+ }
85
+
86
+ const rawText = readFileSync(CONFIG_PATH, "utf-8");
87
+ let raw: unknown;
88
+ try {
89
+ raw = JSON.parse(rawText) as unknown;
90
+ } catch (err) {
91
+ const message = err instanceof Error ? err.message : String(err);
92
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
93
+ }
94
+
95
+ const root =
96
+ raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
97
+ const pdf =
98
+ root.pdf && typeof root.pdf === "object"
99
+ ? (root.pdf as Record<string, unknown>)
100
+ : {};
101
+ const enabled = pdf.enabled !== false;
102
+ const configured = pdf.maxSizeMB;
103
+ const normalized =
104
+ typeof configured === "number" &&
105
+ Number.isFinite(configured) &&
106
+ configured > 0
107
+ ? Math.min(configured, MAX_PDF_MAX_SIZE_MB)
108
+ : DEFAULT_PDF_MAX_SIZE_MB;
109
+ const configuredMaxPages = pdf.maxPages;
110
+ const maxPages =
111
+ typeof configuredMaxPages === "number" &&
112
+ Number.isFinite(configuredMaxPages) &&
113
+ configuredMaxPages > 0
114
+ ? Math.max(1, Math.floor(configuredMaxPages))
115
+ : DEFAULT_MAX_PAGES;
116
+
117
+ const provider =
118
+ typeof pdf.provider === "string" &&
119
+ PDF_PROVIDER_VALUES.has(pdf.provider as PDFProvider)
120
+ ? (pdf.provider as PDFProvider)
121
+ : "auto";
122
+ const datalabMode =
123
+ typeof pdf.datalabMode === "string" &&
124
+ DATALAB_MODE_VALUES.has(pdf.datalabMode as DatalabMode)
125
+ ? (pdf.datalabMode as DatalabMode)
126
+ : normalizeDatalabMode(process.env.DATALAB_MODE);
127
+ const configuredTimeout = pdf.datalabTimeoutMs;
128
+ const datalabTimeoutMs =
129
+ typeof configuredTimeout === "number" &&
130
+ Number.isFinite(configuredTimeout) &&
131
+ configuredTimeout > 0
132
+ ? Math.min(configuredTimeout, MAX_DATALAB_TIMEOUT_MS)
133
+ : DEFAULT_DATALAB_TIMEOUT_MS;
134
+
135
+ return {
136
+ enabled,
137
+ maxSizeMB: normalized,
138
+ maxPages,
139
+ provider,
140
+ datalabMode,
141
+ datalabTimeoutMs,
142
+ };
143
+ }
144
+
145
+ async function getUnpdf() {
146
+ if (
147
+ typeof (Promise as PromiseConstructor & { try?: unknown }).try !==
148
+ "function"
149
+ ) {
150
+ const { default: promiseTry } = await import("promise.try");
151
+ promiseTry.shim();
152
+ }
153
+
154
+ const [unpdf, pdfjs] = await Promise.all([
155
+ import("unpdf"),
156
+ import("unpdf/pdfjs"),
157
+ ]);
158
+ const { VerbosityLevel } = pdfjs as typeof pdfjs & {
159
+ VerbosityLevel: { ERRORS: number };
160
+ };
161
+
162
+ return { getDocumentProxy: unpdf.getDocumentProxy, VerbosityLevel };
163
+ }
164
+
165
+ /**
166
+ * Extract text from a PDF buffer and save it to a Markdown file.
167
+ */
168
+ export async function extractPDFToMarkdown(
169
+ buffer: ArrayBuffer,
170
+ url: string,
171
+ options: PDFExtractOptions = {},
172
+ ): Promise<PDFExtractResult> {
173
+ const {
174
+ maxPages,
175
+ outputDir = DEFAULT_OUTPUT_DIR,
176
+ filename,
177
+ signal,
178
+ geminiTimeoutMs,
179
+ } = options;
180
+
181
+ const pdfConfig = loadPDFConfig();
182
+ const safeMaxPages =
183
+ maxPages === undefined
184
+ ? pdfConfig.maxPages
185
+ : Number.isFinite(maxPages)
186
+ ? Math.max(1, Math.floor(maxPages))
187
+ : DEFAULT_MAX_PAGES;
188
+ const urlTitle = extractTitleFromURL(url);
189
+ const provider = pdfConfig.provider;
190
+ const retrievalOnly = getRetrievalOnlyPolicy().enabled;
191
+ if (retrievalOnly && provider !== "auto" && PDF_PROVIDER_KINDS[provider] === "model") {
192
+ throw retrievalOnlyError(`PDF provider "${provider}"`);
193
+ }
194
+
195
+ if (provider === "auto" || provider === "endpoint") {
196
+ if (provider === "endpoint" && !isEndpointApiAvailable()) {
197
+ throw new Error(
198
+ 'PDF provider "endpoint" requires a configured pdf.endpointUrl',
199
+ );
200
+ }
201
+ try {
202
+ if (isEndpointApiAvailable()) {
203
+ const result = await extractPDFViaEndpoint(buffer, {
204
+ maxPages: safeMaxPages,
205
+ ...(signal ? { signal } : {}),
206
+ });
207
+ return writeMarkdownResult({
208
+ markdownBody: result.markdown,
209
+ title: urlTitle,
210
+ pages: result.pages ?? countPageMarkers(result.markdown),
211
+ outputDir,
212
+ filename,
213
+ url,
214
+ });
215
+ }
216
+ } catch (err) {
217
+ if (shouldRethrowExtractionError(err, signal)) throw err;
218
+ }
219
+ }
220
+
221
+ if (provider === "auto" || provider === "datalab") {
222
+ try {
223
+ if (isDatalabApiAvailable()) {
224
+ const result = await extractPDFViaDatalab(buffer, {
225
+ maxPages: safeMaxPages,
226
+ title: urlTitle,
227
+ mode: pdfConfig.datalabMode,
228
+ timeoutMs: pdfConfig.datalabTimeoutMs,
229
+ ...(signal ? { signal } : {}),
230
+ });
231
+ return writeMarkdownResult({
232
+ markdownBody: result.markdown,
233
+ title: urlTitle,
234
+ pages: result.pages,
235
+ outputDir,
236
+ filename,
237
+ url,
238
+ });
239
+ }
240
+ } catch (err) {
241
+ if (shouldRethrowExtractionError(err, signal)) throw err;
242
+ }
243
+ }
244
+
245
+ if ((provider === "auto" && !retrievalOnly) || provider === "gemini") {
246
+ try {
247
+ if (isGeminiApiAvailable()) {
248
+ const markdownBody = await extractPDFViaGemini(buffer, {
249
+ maxPages: safeMaxPages,
250
+ title: urlTitle,
251
+ ...(signal ? { signal } : {}),
252
+ ...(geminiTimeoutMs !== undefined
253
+ ? { timeoutMs: geminiTimeoutMs }
254
+ : {}),
255
+ });
256
+ return writeMarkdownResult({
257
+ markdownBody,
258
+ title: urlTitle,
259
+ pages: countPageMarkers(markdownBody),
260
+ outputDir,
261
+ filename,
262
+ url,
263
+ });
264
+ }
265
+ } catch (err) {
266
+ if (shouldRethrowExtractionError(err, signal)) throw err;
267
+ }
268
+ }
269
+
270
+ const { getDocumentProxy, VerbosityLevel } = await getUnpdf();
271
+ const pdf = await getDocumentProxy(new Uint8Array(buffer), {
272
+ verbosity: VerbosityLevel.ERRORS,
273
+ });
274
+ const metadata = await pdf.getMetadata();
275
+ const metadataInfo =
276
+ metadata.info && typeof metadata.info === "object"
277
+ ? (metadata.info as Record<string, unknown>)
278
+ : null;
279
+
280
+ const metaTitle =
281
+ typeof metadataInfo?.Title === "string" ? metadataInfo.Title : undefined;
282
+ const metaAuthor =
283
+ typeof metadataInfo?.Author === "string" ? metadataInfo.Author : undefined;
284
+ const title = metaTitle?.trim() || urlTitle;
285
+ const pagesToExtract = Math.min(pdf.numPages, safeMaxPages);
286
+ const truncated = pdf.numPages > safeMaxPages;
287
+ const pages: { pageNum: number; text: string }[] = [];
288
+
289
+ for (let i = 1; i <= pagesToExtract; i++) {
290
+ const page = await pdf.getPage(i);
291
+ const textContent = await page.getTextContent();
292
+ const pageText = textContent.items
293
+ .map((item: unknown) => {
294
+ const textItem = item as { str?: string };
295
+ return textItem.str || "";
296
+ })
297
+ .join(" ")
298
+ .replace(/\s+/g, " ")
299
+ .trim();
300
+
301
+ if (pageText) {
302
+ pages.push({ pageNum: i, text: pageText });
303
+ }
304
+ }
305
+
306
+ const bodyLines: string[] = [];
307
+ for (let i = 0; i < pages.length; i++) {
308
+ if (i > 0) {
309
+ bodyLines.push("");
310
+ bodyLines.push(`<!-- Page ${pages[i].pageNum} -->`);
311
+ bodyLines.push("");
312
+ }
313
+ bodyLines.push(pages[i].text);
314
+ }
315
+
316
+ return writeMarkdownResult({
317
+ markdownBody: bodyLines.join("\n"),
318
+ title,
319
+ pages: pdf.numPages,
320
+ outputDir,
321
+ filename,
322
+ url,
323
+ metaAuthor,
324
+ truncated,
325
+ pagesToExtract,
326
+ });
327
+ }
328
+
329
+ async function writeMarkdownResult(options: {
330
+ markdownBody: string;
331
+ title: string;
332
+ pages: number;
333
+ outputDir: string;
334
+ filename?: string;
335
+ url: string;
336
+ metaAuthor?: string;
337
+ truncated?: boolean;
338
+ pagesToExtract?: number;
339
+ }): Promise<PDFExtractResult> {
340
+ const lines: string[] = [];
341
+ lines.push(`# ${options.title}`);
342
+ lines.push("");
343
+ lines.push(`> Source: ${options.url}`);
344
+ // Providers that report no page count omit the line rather than claim zero pages.
345
+ if (options.pages > 0) {
346
+ lines.push(
347
+ `> Pages: ${options.pages}${options.truncated ? ` (extracted first ${options.pagesToExtract})` : ""}`,
348
+ );
349
+ }
350
+ if (options.metaAuthor) lines.push(`> Author: ${options.metaAuthor}`);
351
+ lines.push("");
352
+ lines.push("---");
353
+ lines.push("");
354
+ if (options.markdownBody) lines.push(options.markdownBody);
355
+
356
+ if (options.truncated) {
357
+ lines.push("");
358
+ lines.push("---");
359
+ lines.push("");
360
+ lines.push(
361
+ `*[Truncated: Only first ${options.pagesToExtract} of ${options.pages} pages extracted]*`,
362
+ );
363
+ }
364
+
365
+ const content = lines.join("\n");
366
+ const outputFilename =
367
+ options.filename || sanitizeFilename(options.title) + ".md";
368
+ const outputPath = join(options.outputDir, outputFilename);
369
+
370
+ await mkdir(options.outputDir, { recursive: true });
371
+ await writeFile(outputPath, content, "utf-8");
372
+
373
+ return {
374
+ title: options.title,
375
+ content,
376
+ outputPath,
377
+ };
378
+ }
379
+
380
+ function countPageMarkers(markdown: string): number {
381
+ return [...markdown.matchAll(PAGE_MARKER_PATTERN)].length;
382
+ }
383
+
384
+ function shouldRethrowExtractionError(
385
+ err: unknown,
386
+ signal?: AbortSignal,
387
+ ): boolean {
388
+ if (signal?.aborted) return true;
389
+ if (err instanceof CredentialResolutionError) return true;
390
+ const message = err instanceof Error ? err.message : String(err);
391
+ return message.startsWith("Failed to parse ");
392
+ }
393
+
394
+ /**
395
+ * Extract a reasonable title from URL
396
+ */
397
+ function extractTitleFromURL(url: string): string {
398
+ try {
399
+ const urlObj = new URL(url);
400
+ const pathname = urlObj.pathname;
401
+
402
+ let filename = basename(pathname, ".pdf");
403
+
404
+ if (urlObj.hostname.includes("arxiv.org")) {
405
+ const match = pathname.match(/\/(?:pdf|abs)\/(\d+\.\d+)/);
406
+ if (match) {
407
+ filename = `arxiv-${match[1]}`;
408
+ }
409
+ }
410
+
411
+ filename = filename.replace(/[_-]+/g, " ").replace(/\s+/g, " ").trim();
412
+
413
+ return filename || "document";
414
+ } catch {
415
+ return "document";
416
+ }
417
+ }
418
+
419
+ /**
420
+ * Sanitize string for use as filename
421
+ */
422
+ function sanitizeFilename(name: string): string {
423
+ return (
424
+ name
425
+ .toLowerCase()
426
+ .replace(/[^a-z0-9\s-]/g, "")
427
+ .replace(/\s+/g, "-")
428
+ .replace(/-+/g, "-")
429
+ .slice(0, 100)
430
+ .replace(/^-|-$/g, "") || "document"
431
+ );
432
+ }
433
+
434
+ /**
435
+ * Check if URL or content-type indicates a PDF
436
+ */
437
+ export function isPDF(url: string, contentType?: string): boolean {
438
+ if (contentType?.includes("application/pdf")) {
439
+ return true;
440
+ }
441
+ try {
442
+ const urlObj = new URL(url);
443
+ return urlObj.pathname.toLowerCase().endsWith(".pdf");
444
+ } catch {
445
+ return false;
446
+ }
447
+ }
package/perplexity.ts ADDED
@@ -0,0 +1,245 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { activityMonitor } from "./activity.ts";
3
+ import type { ExtractedContent } from "./extract.ts";
4
+ import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
5
+ import { formatSearchResultsAsAnswer } from "./search-answer-formatting.ts";
6
+ import { getWebSearchConfigPath, resolveProviderApiUrl, fetchWithCredentialRedirects } from "./utils.ts";
7
+
8
+ const PERPLEXITY_SEARCH_URL = "https://api.perplexity.ai/search";
9
+ const PERPLEXITY_CHAT_URL = "https://api.perplexity.ai/chat/completions";
10
+ const CONFIG_PATH = getWebSearchConfigPath();
11
+ const SEARCH_TIMEOUT_MS = 30_000;
12
+
13
+ const RATE_LIMIT = {
14
+ maxRequests: 10,
15
+ windowMs: 60 * 1000,
16
+ };
17
+
18
+ const requestTimestamps: number[] = [];
19
+
20
+ export interface SearchResult {
21
+ title: string;
22
+ url: string;
23
+ snippet: string;
24
+ /** "generated" when the snippet is text from the provider's own answer around a citation, not text from the page. */
25
+ snippetSource?: "generated";
26
+ }
27
+
28
+ export interface SearchResponse {
29
+ answer: string;
30
+ results: SearchResult[];
31
+ inlineContent?: ExtractedContent[];
32
+ }
33
+
34
+ export interface SearchOptions {
35
+ model?: string;
36
+ numResults?: number;
37
+ recencyFilter?: "day" | "week" | "month" | "year";
38
+ domainFilter?: string[];
39
+ signal?: AbortSignal;
40
+ }
41
+
42
+ interface WebSearchConfig {
43
+ perplexityBaseUrl?: unknown;
44
+ perplexityApiKey?: unknown;
45
+ }
46
+
47
+ let cachedConfig: WebSearchConfig | null = null;
48
+
49
+ function loadConfig(): WebSearchConfig {
50
+ if (cachedConfig) return cachedConfig;
51
+ if (!existsSync(CONFIG_PATH)) {
52
+ cachedConfig = {};
53
+ return cachedConfig;
54
+ }
55
+
56
+ const content = readFileSync(CONFIG_PATH, "utf-8");
57
+ try {
58
+ cachedConfig = JSON.parse(content) as WebSearchConfig;
59
+ return cachedConfig;
60
+ } catch (err) {
61
+ const message = err instanceof Error ? err.message : String(err);
62
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
63
+ }
64
+ }
65
+
66
+ async function getApiKey(signal?: AbortSignal): Promise<string> {
67
+ const key = await resolveCredential({
68
+ provider: "Perplexity",
69
+ configuredValue: loadConfig().perplexityApiKey,
70
+ environmentValue: process.env.PERPLEXITY_API_KEY,
71
+ signal,
72
+ });
73
+ if (!key) {
74
+ throw new Error(
75
+ "Perplexity API key not found. Either:\n" +
76
+ ` 1. Create ${CONFIG_PATH} with { "perplexityApiKey": "your-key" }\n` +
77
+ " 2. Set PERPLEXITY_API_KEY environment variable\n" +
78
+ "Get a key at https://perplexity.ai/settings/api"
79
+ );
80
+ }
81
+ return key;
82
+ }
83
+
84
+ function checkRateLimit(): void {
85
+ const now = Date.now();
86
+ const windowStart = now - RATE_LIMIT.windowMs;
87
+
88
+ while (requestTimestamps.length > 0 && requestTimestamps[0] < windowStart) {
89
+ requestTimestamps.shift();
90
+ }
91
+
92
+ if (requestTimestamps.length >= RATE_LIMIT.maxRequests) {
93
+ const waitMs = requestTimestamps[0] + RATE_LIMIT.windowMs - now;
94
+ throw new Error(`Rate limited. Try again in ${Math.ceil(waitMs / 1000)}s`);
95
+ }
96
+
97
+ requestTimestamps.push(now);
98
+ }
99
+
100
+ function validateDomainFilter(domains: string[]): string[] {
101
+ return domains.filter((d) => {
102
+ const domain = d.startsWith("-") ? d.slice(1) : d;
103
+ return /^[a-zA-Z0-9][a-zA-Z0-9-_.]*\.[a-zA-Z]{2,}$/.test(domain);
104
+ });
105
+ }
106
+
107
+ export function isPerplexityAvailable(): boolean {
108
+ return hasCredentialSource({
109
+ provider: "Perplexity",
110
+ configuredValue: loadConfig().perplexityApiKey,
111
+ environmentValue: process.env.PERPLEXITY_API_KEY,
112
+ });
113
+ }
114
+
115
+ interface PerplexityRequestOptions {
116
+ activityQuery: string;
117
+ signal?: AbortSignal;
118
+ }
119
+
120
+ async function postPerplexity(
121
+ url: string,
122
+ body: Record<string, unknown>,
123
+ options: PerplexityRequestOptions,
124
+ ): Promise<Record<string, unknown>> {
125
+ const apiUrl = resolveProviderApiUrl("perplexity", url, loadConfig().perplexityBaseUrl);
126
+ checkRateLimit();
127
+
128
+ const activityId = activityMonitor.logStart({ type: "api", query: options.activityQuery });
129
+
130
+ activityMonitor.updateRateLimit({
131
+ used: requestTimestamps.length,
132
+ max: RATE_LIMIT.maxRequests,
133
+ oldestTimestamp: requestTimestamps[0] ?? null,
134
+ windowMs: RATE_LIMIT.windowMs,
135
+ });
136
+
137
+ const apiKey = await getApiKey(options.signal);
138
+
139
+ // Reported as a timeout, not an abort: a raw TimeoutError reads as cancellation and would end the search.
140
+ const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
141
+ const timedOut = () => timeout.aborted && !options.signal?.aborted;
142
+ const timeoutError = () => new Error("Perplexity API error 408: request timed out");
143
+
144
+ let response: Response;
145
+ try {
146
+ response = await fetchWithCredentialRedirects(apiUrl, {
147
+ method: "POST",
148
+ headers: {
149
+ Authorization: `Bearer ${apiKey}`,
150
+ "Content-Type": "application/json",
151
+ },
152
+ body: JSON.stringify(body),
153
+ signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout,
154
+ }, ["Authorization"]);
155
+ } catch (err) {
156
+ if (timedOut()) {
157
+ activityMonitor.logError(activityId, "request timed out");
158
+ throw timeoutError();
159
+ }
160
+ const message = err instanceof Error ? err.message : String(err);
161
+ const redactedMessage = redactCredential(message, apiKey);
162
+ if (redactedMessage.toLowerCase().includes("abort")) {
163
+ activityMonitor.logComplete(activityId, 0);
164
+ } else {
165
+ activityMonitor.logError(activityId, redactedMessage);
166
+ }
167
+ if (redactedMessage === message) throw err;
168
+ const redactedError = new Error(redactedMessage);
169
+ if (err instanceof Error) redactedError.name = err.name;
170
+ throw redactedError;
171
+ }
172
+
173
+ activityMonitor.logComplete(activityId, response.status);
174
+
175
+ if (!response.ok) {
176
+ let errorText: string;
177
+ try {
178
+ errorText = redactCredential(await response.text(), apiKey);
179
+ } catch (err) {
180
+ if (timedOut()) throw timeoutError();
181
+ throw err;
182
+ }
183
+ throw new Error(`Perplexity API error ${response.status}: ${errorText}`);
184
+ }
185
+
186
+ try {
187
+ return await response.json();
188
+ } catch (err) {
189
+ if (timedOut()) throw timeoutError();
190
+ const message = err instanceof Error ? err.message : String(err);
191
+ throw new Error(`Perplexity API returned invalid JSON: ${message}`);
192
+ }
193
+ }
194
+
195
+ export async function searchWithPerplexity(query: string, options: SearchOptions = {}): Promise<SearchResponse> {
196
+ const numResults = typeof options.numResults === "number" && Number.isFinite(options.numResults)
197
+ ? Math.max(1, Math.min(Math.floor(options.numResults), 20))
198
+ : 5;
199
+
200
+ const requestBody: Record<string, unknown> = {
201
+ query,
202
+ max_results: numResults,
203
+ search_type: "fast",
204
+ search_context_size: "medium",
205
+ };
206
+
207
+ if (options.recencyFilter) {
208
+ requestBody.search_recency_filter = options.recencyFilter;
209
+ }
210
+
211
+ if (options.domainFilter && options.domainFilter.length > 0) {
212
+ const validated = validateDomainFilter(options.domainFilter);
213
+ if (validated.length > 0) {
214
+ requestBody.search_domain_filter = validated;
215
+ }
216
+ }
217
+
218
+ const data = await postPerplexity(PERPLEXITY_SEARCH_URL, requestBody, { activityQuery: query, signal: options.signal });
219
+
220
+ const results: SearchResult[] = [];
221
+ for (const entry of Array.isArray(data.results) ? data.results : []) {
222
+ if (!entry || typeof entry !== "object" || typeof entry.url !== "string" || !entry.url) continue;
223
+ results.push({
224
+ title: typeof entry.title === "string" && entry.title.trim() ? entry.title.trim() : `Source ${results.length + 1}`,
225
+ url: entry.url,
226
+ snippet: typeof entry.snippet === "string" ? entry.snippet.trim() : "",
227
+ });
228
+ if (results.length >= numResults) break;
229
+ }
230
+
231
+ return { answer: formatSearchResultsAsAnswer(results), results };
232
+ }
233
+
234
+ /** Asks Sonar for a prose answer. The Search API returns only ranked pages, so prompts that need prose use this. */
235
+ export async function askPerplexity(prompt: string, options: { signal?: AbortSignal } = {}): Promise<string> {
236
+ const data = await postPerplexity(PERPLEXITY_CHAT_URL, {
237
+ model: "sonar",
238
+ messages: [{ role: "user", content: prompt }],
239
+ max_tokens: 1024,
240
+ return_related_questions: false,
241
+ }, { activityQuery: prompt, signal: options.signal });
242
+
243
+ const content = (data.choices as Array<{ message?: { content?: unknown } }> | undefined)?.[0]?.message?.content;
244
+ return typeof content === "string" ? content : "";
245
+ }