@abhishek944/pi-web-access 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ASTACK.md +23 -0
- package/CHANGELOG.md +1289 -0
- package/LICENSE +21 -0
- package/README.md +1215 -2
- package/SECURITY.md +5 -0
- package/abortable.ts +17 -0
- package/activity.ts +101 -0
- package/anysearch.ts +188 -0
- package/auth-fetch.ts +152 -0
- package/baizhi.ts +124 -0
- package/banner.png +0 -0
- package/bocha.ts +203 -0
- package/brave-rate-limit.ts +176 -0
- package/brave.ts +247 -0
- package/brightdata-unlocker.ts +272 -0
- package/ceramic.ts +220 -0
- package/chrome-cookies.ts +752 -0
- package/cloudflare-search.ts +237 -0
- package/content-find.ts +255 -0
- package/crawl4ai.ts +196 -0
- package/credential-source.ts +242 -0
- package/curator-page.ts +3607 -0
- package/curator-run.ts +45 -0
- package/curator-server.ts +761 -0
- package/custom-search.ts +226 -0
- package/data-uri-sanitize.ts +406 -0
- package/datalab-pdf-extract.ts +568 -0
- package/declared-web-links.ts +173 -0
- package/deepseek.ts +377 -0
- package/degoog.ts +323 -0
- package/dist/index.js +28286 -0
- package/dist/mcp-cli.js +29186 -0
- package/dist/pi-mcp.js +20855 -0
- package/dist/types/abortable.d.ts +2 -0
- package/dist/types/activity.d.ts +33 -0
- package/dist/types/anysearch.d.ts +7 -0
- package/dist/types/auth-fetch.d.ts +14 -0
- package/dist/types/baizhi.d.ts +3 -0
- package/dist/types/bocha.d.ts +3 -0
- package/dist/types/brave-rate-limit.d.ts +35 -0
- package/dist/types/brave.d.ts +3 -0
- package/dist/types/brightdata-unlocker.d.ts +11 -0
- package/dist/types/ceramic.d.ts +3 -0
- package/dist/types/chrome-cookies.d.ts +44 -0
- package/dist/types/cloudflare-search.d.ts +4 -0
- package/dist/types/content-find.d.ts +10 -0
- package/dist/types/crawl4ai.d.ts +8 -0
- package/dist/types/credential-source.d.ts +29 -0
- package/dist/types/curator-page.d.ts +5 -0
- package/dist/types/curator-run.d.ts +10 -0
- package/dist/types/curator-server.d.ts +72 -0
- package/dist/types/custom-search.d.ts +22 -0
- package/dist/types/data-uri-sanitize.d.ts +20 -0
- package/dist/types/datalab-pdf-extract.d.ts +59 -0
- package/dist/types/declared-web-links.d.ts +7 -0
- package/dist/types/deepseek.d.ts +13 -0
- package/dist/types/degoog.d.ts +3 -0
- package/dist/types/domain-filter-normalization.d.ts +9 -0
- package/dist/types/duckduckgo-rate-limit.d.ts +52 -0
- package/dist/types/duckduckgo.d.ts +6 -0
- package/dist/types/endpoint-pdf-extract.d.ts +22 -0
- package/dist/types/exa.d.ts +17 -0
- package/dist/types/extract.d.ts +70 -0
- package/dist/types/feature-config.d.ts +2 -0
- package/dist/types/fetch-params.d.ts +39 -0
- package/dist/types/field-extract.d.ts +37 -0
- package/dist/types/firecrawl.d.ts +18 -0
- package/dist/types/gemini-adc.d.ts +9 -0
- package/dist/types/gemini-api.d.ts +37 -0
- package/dist/types/gemini-pdf-extract.d.ts +8 -0
- package/dist/types/gemini-search.d.ts +76 -0
- package/dist/types/gemini-url-context.d.ts +3 -0
- package/dist/types/gemini-web-config.d.ts +25 -0
- package/dist/types/gemini-web.d.ts +31 -0
- package/dist/types/github-api.d.ts +6 -0
- package/dist/types/github-extract.d.ts +19 -0
- package/dist/types/github-issue-pr.d.ts +28 -0
- package/dist/types/index.d.ts +53 -0
- package/dist/types/jina-search.d.ts +7 -0
- package/dist/types/kagi.d.ts +14 -0
- package/dist/types/keenable.d.ts +3 -0
- package/dist/types/kimi-search.d.ts +4 -0
- package/dist/types/linkup.d.ts +5 -0
- package/dist/types/mcp-cli.d.ts +2 -0
- package/dist/types/mcp-server.d.ts +10 -0
- package/dist/types/mcp-tool-definitions.d.ts +16 -0
- package/dist/types/mistral-search.d.ts +3 -0
- package/dist/types/ninerouter.d.ts +3 -0
- package/dist/types/offtopic-judge.d.ts +26 -0
- package/dist/types/ollama.d.ts +14 -0
- package/dist/types/openai-search.d.ts +23 -0
- package/dist/types/page-query.d.ts +22 -0
- package/dist/types/parallel-mcp.d.ts +10 -0
- package/dist/types/parallel.d.ts +13 -0
- package/dist/types/pdf-extract.d.ts +44 -0
- package/dist/types/perplexity.d.ts +26 -0
- package/dist/types/pi-mcp.d.ts +56 -0
- package/dist/types/pi-session-results.d.ts +8 -0
- package/dist/types/querit.d.ts +9 -0
- package/dist/types/query-rewrite.d.ts +2 -0
- package/dist/types/render-search-error.d.ts +56 -0
- package/dist/types/retrieval-only.d.ts +78 -0
- package/dist/types/rsc-extract.d.ts +11 -0
- package/dist/types/search-answer-formatting.d.ts +7 -0
- package/dist/types/search-result-count-normalization.d.ts +1 -0
- package/dist/types/searchinfinity.d.ts +7 -0
- package/dist/types/searxng.d.ts +3 -0
- package/dist/types/source-check.d.ts +102 -0
- package/dist/types/ssrf-protection.d.ts +66 -0
- package/dist/types/storage.d.ts +69 -0
- package/dist/types/summary-model-scope.d.ts +33 -0
- package/dist/types/summary-review.d.ts +30 -0
- package/dist/types/tabstack.d.ts +5 -0
- package/dist/types/tavily.d.ts +7 -0
- package/dist/types/tinyfish.d.ts +10 -0
- package/dist/types/tool-activation.d.ts +7 -0
- package/dist/types/tool-arguments.d.ts +1 -0
- package/dist/types/upgrade-notice.d.ts +6 -0
- package/dist/types/utils.d.ts +55 -0
- package/dist/types/valyu.d.ts +5 -0
- package/dist/types/video-extract.d.ts +15 -0
- package/dist/types/web-tool-contract.d.ts +98 -0
- package/dist/types/web-tool-core.d.ts +227 -0
- package/dist/types/xai-search.d.ts +12 -0
- package/dist/types/you.d.ts +3 -0
- package/dist/types/youtube-extract.d.ts +29 -0
- package/dist/types/zai.d.ts +3 -0
- package/docs/pi-mcp.md +41 -0
- package/domain-filter-normalization.ts +44 -0
- package/duckduckgo-rate-limit.ts +205 -0
- package/duckduckgo.ts +123 -0
- package/endpoint-pdf-extract.ts +225 -0
- package/exa.ts +620 -0
- package/extract.ts +1721 -0
- package/feature-config.ts +29 -0
- package/fetch-params.ts +147 -0
- package/field-extract.ts +347 -0
- package/firecrawl.ts +476 -0
- package/gemini-adc.ts +345 -0
- package/gemini-api.ts +368 -0
- package/gemini-pdf-extract.ts +108 -0
- package/gemini-search.ts +1162 -0
- package/gemini-url-context.ts +128 -0
- package/gemini-web-config.ts +131 -0
- package/gemini-web.ts +527 -0
- package/github-api.ts +197 -0
- package/github-extract.ts +1064 -0
- package/github-issue-pr.ts +717 -0
- package/index.ts +2819 -0
- package/jina-search.ts +275 -0
- package/kagi.ts +257 -0
- package/keenable.ts +222 -0
- package/kimi-search.ts +209 -0
- package/linkup.ts +170 -0
- package/mcp-cli.ts +40 -0
- package/mcp-server.ts +84 -0
- package/mcp-tool-definitions.ts +143 -0
- package/mistral-search.ts +268 -0
- package/ninerouter.ts +92 -0
- package/offtopic-judge.ts +72 -0
- package/ollama.ts +237 -0
- package/openai-search.ts +855 -0
- package/package.json +108 -4
- package/page-query.ts +185 -0
- package/parallel-mcp.ts +255 -0
- package/parallel.ts +373 -0
- package/pdf-extract.ts +447 -0
- package/perplexity.ts +245 -0
- package/pi-mcp.ts +139 -0
- package/pi-session-results.ts +40 -0
- package/pi-web-fetch-demo.mp4 +0 -0
- package/promise-try.d.ts +7 -0
- package/querit.ts +394 -0
- package/query-rewrite.ts +84 -0
- package/render-search-error.ts +170 -0
- package/retrieval-only.ts +102 -0
- package/rsc-extract.ts +338 -0
- package/search-answer-formatting.ts +11 -0
- package/search-result-count-normalization.ts +4 -0
- package/searchinfinity.ts +246 -0
- package/searxng.ts +236 -0
- package/source-check.ts +269 -0
- package/ssrf-protection.ts +602 -0
- package/storage.ts +547 -0
- package/summary-model-scope.ts +72 -0
- package/summary-review.ts +476 -0
- package/tabstack.ts +289 -0
- package/tavily.ts +257 -0
- package/tinyfish.ts +373 -0
- package/tool-activation.ts +169 -0
- package/tool-arguments.ts +23 -0
- package/upgrade-notice.ts +47 -0
- package/utils.ts +693 -0
- package/valyu.ts +177 -0
- package/video-extract.ts +398 -0
- package/web-tool-contract.ts +93 -0
- package/web-tool-core.ts +1810 -0
- package/xai-search.ts +443 -0
- package/you.ts +165 -0
- package/youtube-extract.ts +336 -0
- package/zai.ts +161 -0
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { awaitWithAbort } from "./abortable.ts";
|
|
4
|
+
import { defaultSleep, formatWait } from "./brave-rate-limit.ts";
|
|
5
|
+
|
|
6
|
+
// DuckDuckGo has no API quota, but it shows its bot check to the whole client IP
|
|
7
|
+
// (browsers included) once too many requests come from it, and keeps it up for 7 to 30
|
|
8
|
+
// minutes. Changing the User-Agent, TLS fingerprint or endpoint does not help. Tests from
|
|
9
|
+
// one home IP: 2s apart was blocked after 3 to 34 searches, 5s apart after 22 searches in
|
|
10
|
+
// 10 minutes, 10s apart back to back after 47 searches; 10s apart with at most 10 per 10
|
|
11
|
+
// minutes ran 60 searches in 54 minutes from three processes sharing one budget with no
|
|
12
|
+
// bot check. A retry soon after a block brings it back, hence the long, doubling pause.
|
|
13
|
+
|
|
14
|
+
const DEFAULT_MIN_INTERVAL_MS = 10_000;
|
|
15
|
+
const DEFAULT_WINDOW_MS = 10 * 60_000;
|
|
16
|
+
const DEFAULT_MAX_STARTS = 10;
|
|
17
|
+
const DEFAULT_COOLDOWN_MS = 30 * 60_000;
|
|
18
|
+
const DEFAULT_MAX_COOLDOWN_MS = 2 * 60 * 60_000;
|
|
19
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
20
|
+
/** Part of the deadline kept for the request itself; a search that would start later fails at once. */
|
|
21
|
+
const REQUEST_ALLOWANCE_MS = 10_000;
|
|
22
|
+
|
|
23
|
+
export class DuckDuckGoBotCheckError extends Error {
|
|
24
|
+
constructor(status: number) {
|
|
25
|
+
// "rate limited" makes search routing classify this as quota.
|
|
26
|
+
super(`DuckDuckGo blocked the request with a bot check (HTTP ${status}, rate limited); use another search provider`);
|
|
27
|
+
this.name = "DuckDuckGoBotCheckError";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface DuckDuckGoRateLimitOptions {
|
|
32
|
+
now?: () => number;
|
|
33
|
+
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
34
|
+
minIntervalMs?: number;
|
|
35
|
+
/** At most `maxStarts` searches start in any `windowMs`. */
|
|
36
|
+
windowMs?: number;
|
|
37
|
+
maxStarts?: number;
|
|
38
|
+
cooldownMs?: number;
|
|
39
|
+
maxCooldownMs?: number;
|
|
40
|
+
/** Deadline per search, counted from when it is called. */
|
|
41
|
+
timeoutMs?: number;
|
|
42
|
+
/** File that shares the bot-check pause with other processes; unset keeps it in this process. */
|
|
43
|
+
statePath?: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
interface Cooldown {
|
|
47
|
+
blockedUntil: number;
|
|
48
|
+
/** Pause to apply after the next bot check. */
|
|
49
|
+
nextCooldownMs: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function cooldownError(remainingMs: number): Error {
|
|
53
|
+
return new Error(`DuckDuckGo showed a bot check recently; not retrying for ${formatWait(remainingMs)} so the block can clear (rate limited); use another search provider`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export class DuckDuckGoRateLimit {
|
|
57
|
+
private queue: Promise<void> = Promise.resolve();
|
|
58
|
+
/** Searches queued that have not started yet. */
|
|
59
|
+
private waiting = 0;
|
|
60
|
+
/** Actual start times of the latest `maxStarts` searches, oldest first. */
|
|
61
|
+
private starts: number[] = [];
|
|
62
|
+
private cooldown: Cooldown;
|
|
63
|
+
private readonly now: () => number;
|
|
64
|
+
private readonly sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
65
|
+
private readonly minIntervalMs: number;
|
|
66
|
+
private readonly windowMs: number;
|
|
67
|
+
private readonly maxStarts: number;
|
|
68
|
+
private readonly cooldownMs: number;
|
|
69
|
+
private readonly maxCooldownMs: number;
|
|
70
|
+
private readonly timeoutMs: number;
|
|
71
|
+
private readonly statePath: string | undefined;
|
|
72
|
+
|
|
73
|
+
constructor(options: DuckDuckGoRateLimitOptions = {}) {
|
|
74
|
+
this.now = options.now ?? Date.now;
|
|
75
|
+
this.sleep = options.sleep ?? defaultSleep;
|
|
76
|
+
this.minIntervalMs = options.minIntervalMs ?? DEFAULT_MIN_INTERVAL_MS;
|
|
77
|
+
this.windowMs = options.windowMs ?? DEFAULT_WINDOW_MS;
|
|
78
|
+
this.maxStarts = Math.max(1, options.maxStarts ?? DEFAULT_MAX_STARTS);
|
|
79
|
+
this.cooldownMs = options.cooldownMs ?? DEFAULT_COOLDOWN_MS;
|
|
80
|
+
this.maxCooldownMs = options.maxCooldownMs ?? DEFAULT_MAX_COOLDOWN_MS;
|
|
81
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
82
|
+
this.statePath = options.statePath;
|
|
83
|
+
this.cooldown = { blockedUntil: 0, nextCooldownMs: this.cooldownMs };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Queues `operation` behind earlier searches and runs it with a signal that fires on the
|
|
88
|
+
* caller's abort or when the deadline passes. A search that cannot start before its
|
|
89
|
+
* deadline fails at once as rate limited, so routing moves on without waiting. A passed
|
|
90
|
+
* deadline rejects with a "timed out" error rather than an abort, so search routing
|
|
91
|
+
* treats it as a network failure and can fall back.
|
|
92
|
+
*/
|
|
93
|
+
async run<T>(operation: (signal: AbortSignal) => Promise<T>, callerSignal?: AbortSignal): Promise<T> {
|
|
94
|
+
if (callerSignal?.aborted) throw new Error("Aborted");
|
|
95
|
+
const now = this.now();
|
|
96
|
+
const latestStart = now + Math.max(0, this.timeoutMs - REQUEST_ALLOWANCE_MS);
|
|
97
|
+
this.throwIfBlocked(now);
|
|
98
|
+
const slot = this.nextSlot(now, this.waiting + 1);
|
|
99
|
+
if (slot > latestStart) throw this.busyError(slot - now);
|
|
100
|
+
|
|
101
|
+
const deadline = AbortSignal.timeout(this.timeoutMs);
|
|
102
|
+
const signal = callerSignal ? AbortSignal.any([deadline, callerSignal]) : deadline;
|
|
103
|
+
this.waiting++;
|
|
104
|
+
const started = this.queue.then(() => this.waitForSlot(signal, latestStart)).finally(() => { this.waiting--; });
|
|
105
|
+
this.queue = started.then(() => undefined, () => undefined);
|
|
106
|
+
try {
|
|
107
|
+
// Let a search give up while still queued without unblocking the queue early.
|
|
108
|
+
return await awaitWithAbort(started.then(() => this.attempt(operation, signal)), signal);
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (deadline.aborted && !callerSignal?.aborted) {
|
|
111
|
+
throw new Error(`DuckDuckGo request timed out after ${formatWait(this.timeoutMs)}`);
|
|
112
|
+
}
|
|
113
|
+
throw error;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Start time of the `count`th search from now, given the searches already started. */
|
|
118
|
+
private nextSlot(now: number, count: number): number {
|
|
119
|
+
const starts = [...this.starts];
|
|
120
|
+
let slot = now;
|
|
121
|
+
for (let i = 0; i < count; i++) {
|
|
122
|
+
slot = Math.max(now, (starts.at(-1) ?? Number.NEGATIVE_INFINITY) + this.minIntervalMs);
|
|
123
|
+
if (starts.length >= this.maxStarts) slot = Math.max(slot, starts[starts.length - this.maxStarts] + this.windowMs);
|
|
124
|
+
starts.push(slot);
|
|
125
|
+
}
|
|
126
|
+
return slot;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Runs at the head of the queue, so spacing is measured from the previous search's actual start. */
|
|
130
|
+
private async waitForSlot(signal: AbortSignal, latestStart: number): Promise<void> {
|
|
131
|
+
for (;;) {
|
|
132
|
+
if (signal.aborted) throw new Error("Aborted");
|
|
133
|
+
const now = this.now();
|
|
134
|
+
this.throwIfBlocked(now);
|
|
135
|
+
const slot = this.nextSlot(now, 1);
|
|
136
|
+
if (slot <= now) {
|
|
137
|
+
this.starts.push(now);
|
|
138
|
+
if (this.starts.length > this.maxStarts) this.starts.shift();
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (slot > latestStart) throw this.busyError(slot - now);
|
|
142
|
+
await this.sleep(slot - now, signal);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
private busyError(waitMs: number): Error {
|
|
147
|
+
return new Error(`DuckDuckGo is limited to one search every ${formatWait(this.minIntervalMs)} and ${this.maxStarts} every ${formatWait(this.windowMs)} in this process to avoid its bot check; the next free slot is in ${formatWait(waitMs)} (rate limited); use another search provider`);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
private throwIfBlocked(now: number): void {
|
|
151
|
+
this.loadSharedCooldown();
|
|
152
|
+
const remainingMs = this.cooldown.blockedUntil - now;
|
|
153
|
+
if (remainingMs > 0) throw cooldownError(remainingMs);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
private async attempt<T>(operation: (signal: AbortSignal) => Promise<T>, signal: AbortSignal): Promise<T> {
|
|
157
|
+
try {
|
|
158
|
+
const result = await operation(signal);
|
|
159
|
+
this.loadSharedCooldown();
|
|
160
|
+
if (this.cooldown.nextCooldownMs !== this.cooldownMs && this.cooldown.blockedUntil <= this.now()) {
|
|
161
|
+
this.cooldown = { ...this.cooldown, nextCooldownMs: this.cooldownMs };
|
|
162
|
+
this.saveSharedCooldown();
|
|
163
|
+
}
|
|
164
|
+
return result;
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (error instanceof DuckDuckGoBotCheckError) {
|
|
167
|
+
this.loadSharedCooldown();
|
|
168
|
+
const now = this.now();
|
|
169
|
+
// Searches already in flight see the same block; count it once.
|
|
170
|
+
if (this.cooldown.blockedUntil <= now) {
|
|
171
|
+
const pauseMs = this.cooldown.nextCooldownMs;
|
|
172
|
+
this.cooldown = { blockedUntil: now + pauseMs, nextCooldownMs: Math.min(pauseMs * 2, this.maxCooldownMs) };
|
|
173
|
+
this.saveSharedCooldown();
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// The state file is best effort: if it cannot be read or written, this process keeps
|
|
181
|
+
// its own pause, and a search never fails or loses its result because of the file.
|
|
182
|
+
private loadSharedCooldown(): void {
|
|
183
|
+
if (!this.statePath) return;
|
|
184
|
+
try {
|
|
185
|
+
const saved = JSON.parse(readFileSync(this.statePath, "utf8")) as Partial<Cooldown>;
|
|
186
|
+
const { blockedUntil, nextCooldownMs } = saved;
|
|
187
|
+
if (typeof blockedUntil !== "number" || typeof nextCooldownMs !== "number" || !(nextCooldownMs > 0)) return;
|
|
188
|
+
// A pause longer than the cap comes from a clock that has since moved back, or a damaged file.
|
|
189
|
+
if (!(blockedUntil <= this.now() + this.maxCooldownMs)) return;
|
|
190
|
+
if (blockedUntil >= this.cooldown.blockedUntil) {
|
|
191
|
+
this.cooldown = { blockedUntil, nextCooldownMs: Math.min(nextCooldownMs, this.maxCooldownMs) };
|
|
192
|
+
}
|
|
193
|
+
} catch {}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
private saveSharedCooldown(): void {
|
|
197
|
+
if (!this.statePath) return;
|
|
198
|
+
try {
|
|
199
|
+
mkdirSync(dirname(this.statePath), { recursive: true, mode: 0o700 });
|
|
200
|
+
const tmpPath = `${this.statePath}.${process.pid}.tmp`;
|
|
201
|
+
writeFileSync(tmpPath, JSON.stringify(this.cooldown), { mode: 0o600 });
|
|
202
|
+
renameSync(tmpPath, this.statePath);
|
|
203
|
+
} catch {}
|
|
204
|
+
}
|
|
205
|
+
}
|
package/duckduckgo.ts
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { activityMonitor } from "./activity.ts";
|
|
2
|
+
import { normalizeDomain } from "./domain-filter-normalization.ts";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { DuckDuckGoBotCheckError, DuckDuckGoRateLimit, type DuckDuckGoRateLimitOptions } from "./duckduckgo-rate-limit.ts";
|
|
5
|
+
import type { SearchOptions, SearchResult, SearchResponse } from "./perplexity.ts";
|
|
6
|
+
import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
|
|
7
|
+
import { getWebSearchConfigDir } from "./utils.ts";
|
|
8
|
+
|
|
9
|
+
const SEARCH_URL = "https://html.duckduckgo.com/html/";
|
|
10
|
+
/** Bot-check pause, shared by every Pi process using this config directory. */
|
|
11
|
+
const STATE_FILE = "duckduckgo-cooldown.json";
|
|
12
|
+
let rateLimit: DuckDuckGoRateLimit | null = null;
|
|
13
|
+
|
|
14
|
+
function getRateLimit(): DuckDuckGoRateLimit {
|
|
15
|
+
return rateLimit ??= new DuckDuckGoRateLimit({ statePath: join(getWebSearchConfigDir(), STATE_FILE) });
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Replace the request spacing and bot-check cooldown state (for tests); without `statePath` nothing is shared. */
|
|
19
|
+
export function resetDuckDuckGoRateLimit(options?: DuckDuckGoRateLimitOptions): void {
|
|
20
|
+
rateLimit = new DuckDuckGoRateLimit(options);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
interface NormalizedDomainFilters {
|
|
24
|
+
allowed: string[];
|
|
25
|
+
blocked: string[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function normalizeDomainFilters(domainFilter: string[] | undefined): NormalizedDomainFilters {
|
|
29
|
+
const filters: NormalizedDomainFilters = { allowed: [], blocked: [] };
|
|
30
|
+
for (const raw of domainFilter ?? []) {
|
|
31
|
+
const domain = normalizeDomain(raw);
|
|
32
|
+
if (!domain) continue;
|
|
33
|
+
const target = raw.trim().startsWith("-") ? filters.blocked : filters.allowed;
|
|
34
|
+
if (!target.includes(domain)) target.push(domain);
|
|
35
|
+
}
|
|
36
|
+
return filters;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function hostMatchesDomain(hostname: string, domain: string): boolean {
|
|
40
|
+
return hostname === domain || hostname.endsWith(`.${domain}`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function matchesDomainFilters(url: string, filters: NormalizedDomainFilters): boolean {
|
|
44
|
+
if (filters.allowed.length === 0 && filters.blocked.length === 0) return true;
|
|
45
|
+
const hostname = new URL(url).hostname.toLowerCase();
|
|
46
|
+
if (filters.allowed.length > 0 && !filters.allowed.some(domain => hostMatchesDomain(hostname, domain))) return false;
|
|
47
|
+
return !filters.blocked.some(domain => hostMatchesDomain(hostname, domain));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function decodeResultUrl(href: string): string | null {
|
|
51
|
+
try {
|
|
52
|
+
const link = new URL(href, SEARCH_URL);
|
|
53
|
+
const destination = link.searchParams.get("uddg") ?? link.href;
|
|
54
|
+
const url = new URL(destination);
|
|
55
|
+
return url.protocol === "http:" || url.protocol === "https:" ? url.href : null;
|
|
56
|
+
} catch {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function isDuckDuckGoAvailable(): boolean {
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function searchWithDuckDuckGo(query: string, options: SearchOptions = {}): Promise<SearchResponse> {
|
|
66
|
+
const url = new URL(SEARCH_URL);
|
|
67
|
+
url.searchParams.set("q", query);
|
|
68
|
+
const activityId = activityMonitor.logStart({ type: "api", query });
|
|
69
|
+
|
|
70
|
+
try {
|
|
71
|
+
return await getRateLimit().run(async signal => {
|
|
72
|
+
const response = await fetch(url, {
|
|
73
|
+
method: "GET",
|
|
74
|
+
headers: {
|
|
75
|
+
Accept: "text/html",
|
|
76
|
+
"User-Agent": "Mozilla/5.0 (compatible; pi-web-access/1.0; +https://github.com/nicobailon/pi-web-access)",
|
|
77
|
+
},
|
|
78
|
+
signal,
|
|
79
|
+
});
|
|
80
|
+
if (!response.ok) {
|
|
81
|
+
const body = await response.text();
|
|
82
|
+
throw new Error(`DuckDuckGo search error ${response.status}: ${body.slice(0, 300)}`);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const { parseHTML } = await import("linkedom");
|
|
86
|
+
const { document } = parseHTML(await response.text());
|
|
87
|
+
// The bot check answers 202 or a challenge page.
|
|
88
|
+
if (response.status === 202 || document.querySelector(".anomaly-modal__box, #challenge-form")) {
|
|
89
|
+
throw new DuckDuckGoBotCheckError(response.status);
|
|
90
|
+
}
|
|
91
|
+
const filters = normalizeDomainFilters(options.domainFilter);
|
|
92
|
+
const results: SearchResult[] = [];
|
|
93
|
+
let parseableResults = 0;
|
|
94
|
+
for (const container of document.querySelectorAll(".result")) {
|
|
95
|
+
if (container.classList.contains("result--ad")) continue;
|
|
96
|
+
const anchor = container.querySelector(".result__a");
|
|
97
|
+
const title = anchor?.textContent?.trim() ?? "";
|
|
98
|
+
const href = anchor?.getAttribute("href")?.trim() ?? "";
|
|
99
|
+
const resultUrl = href ? decodeResultUrl(href) : null;
|
|
100
|
+
if (!title || !resultUrl) continue;
|
|
101
|
+
parseableResults++;
|
|
102
|
+
if (!matchesDomainFilters(resultUrl, filters)) continue;
|
|
103
|
+
const snippet = container.querySelector(".result__snippet")?.textContent?.trim() ?? "";
|
|
104
|
+
results.push({ title, url: resultUrl, snippet });
|
|
105
|
+
if (results.length >= normalizeSearchResultCount(options.numResults)) break;
|
|
106
|
+
}
|
|
107
|
+
if (parseableResults === 0 && !document.querySelector(".no-results__message")) {
|
|
108
|
+
throw new Error("DuckDuckGo returned no parseable results (invalid response)");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
112
|
+
const answer = results.map(result => result.snippet
|
|
113
|
+
? `${result.snippet}\nSource: ${result.title} (${result.url})`
|
|
114
|
+
: `Source: ${result.title} (${result.url})`).join("\n\n");
|
|
115
|
+
return { answer, results };
|
|
116
|
+
}, options.signal);
|
|
117
|
+
} catch (err) {
|
|
118
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
119
|
+
if (message.toLowerCase().includes("abort")) activityMonitor.logComplete(activityId, 0);
|
|
120
|
+
else activityMonitor.logError(activityId, message);
|
|
121
|
+
throw err;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
3
|
+
import { fetchRemoteUrl, loadSsrfConfig, type Lookup } from "./ssrf-protection.ts";
|
|
4
|
+
import { getWebSearchConfigPath, isLoopbackHostname } from "./utils.ts";
|
|
5
|
+
|
|
6
|
+
const DEFAULT_TIMEOUT_MS = 120_000;
|
|
7
|
+
const MAX_POLL_INTERVAL_MS = 3_000;
|
|
8
|
+
const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
|
|
9
|
+
const MAX_ERROR_BODY_BYTES = 300;
|
|
10
|
+
const CONFIG_PATH = getWebSearchConfigPath();
|
|
11
|
+
|
|
12
|
+
export interface EndpointPDFExtractOptions {
|
|
13
|
+
maxPages: number;
|
|
14
|
+
signal?: AbortSignal;
|
|
15
|
+
timeoutMs?: number;
|
|
16
|
+
lookup?: Lookup;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface EndpointPDFExtractResult {
|
|
20
|
+
markdown: string;
|
|
21
|
+
pages?: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function pdfSection(): Record<string, unknown> {
|
|
25
|
+
if (!existsSync(CONFIG_PATH)) return {};
|
|
26
|
+
let parsed: unknown;
|
|
27
|
+
try {
|
|
28
|
+
parsed = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));
|
|
29
|
+
} catch (err) {
|
|
30
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
31
|
+
throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
|
|
32
|
+
}
|
|
33
|
+
const pdf = (parsed as { pdf?: unknown } | null)?.pdf;
|
|
34
|
+
return pdf && typeof pdf === "object" ? (pdf as Record<string, unknown>) : {};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function normalizeString(value: unknown): string | null {
|
|
38
|
+
if (typeof value !== "string") return null;
|
|
39
|
+
const normalized = value.trim();
|
|
40
|
+
return normalized.length > 0 ? normalized : null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Null means the provider is not configured. Trailing slashes are stripped so the
|
|
45
|
+
* relative `jobs/<id>` poll URL resolves beside the parse path.
|
|
46
|
+
*/
|
|
47
|
+
export function getEndpointUrl(): string | null {
|
|
48
|
+
const configured =
|
|
49
|
+
normalizeString(process.env.PDF_ENDPOINT_URL) ??
|
|
50
|
+
normalizeString(pdfSection().endpointUrl);
|
|
51
|
+
if (!configured) return null;
|
|
52
|
+
const protocol = URL.parse(configured)?.protocol;
|
|
53
|
+
if (protocol !== "http:" && protocol !== "https:") {
|
|
54
|
+
throw new Error(
|
|
55
|
+
`Failed to parse pdf.endpointUrl: expected an absolute http(s) URL, got "${configured}"`,
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
return configured.replace(/\/+$/, "");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function getEndpointTimeoutMs(): number {
|
|
62
|
+
const configured = pdfSection().endpointTimeoutMs;
|
|
63
|
+
if (typeof configured === "number" && Number.isFinite(configured) && configured > 0) {
|
|
64
|
+
return Math.min(configured, 300_000);
|
|
65
|
+
}
|
|
66
|
+
return DEFAULT_TIMEOUT_MS;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function isEndpointApiAvailable(): boolean {
|
|
70
|
+
try {
|
|
71
|
+
return getEndpointUrl() !== null;
|
|
72
|
+
} catch {
|
|
73
|
+
// A malformed URL is surfaced as a fatal config error by the extract
|
|
74
|
+
// call itself; availability only reports whether it is configured.
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Read at most `maxBytes`, cancelling the stream at the cap. Error previews
|
|
81
|
+
* keep the prefix; JSON bodies past the cap are an error.
|
|
82
|
+
*/
|
|
83
|
+
async function readCapped(response: Response, maxBytes: number, overflowThrows: boolean): Promise<string> {
|
|
84
|
+
const reader = response.body?.getReader();
|
|
85
|
+
if (!reader) return "";
|
|
86
|
+
const decoder = new TextDecoder();
|
|
87
|
+
let text = "";
|
|
88
|
+
let received = 0;
|
|
89
|
+
for (;;) {
|
|
90
|
+
const { done, value } = await reader.read();
|
|
91
|
+
if (done) return text + decoder.decode();
|
|
92
|
+
const room = maxBytes - received;
|
|
93
|
+
received += value.byteLength;
|
|
94
|
+
// Stop at exactly the cap too: a full preview must not wait on a parser that stalls after it.
|
|
95
|
+
if (received >= maxBytes) {
|
|
96
|
+
await reader.cancel();
|
|
97
|
+
if (overflowThrows && received > maxBytes) {
|
|
98
|
+
throw new Error("PDF parser endpoint returned an oversized response");
|
|
99
|
+
}
|
|
100
|
+
return text + decoder.decode(value.subarray(0, room));
|
|
101
|
+
}
|
|
102
|
+
text += decoder.decode(value, { stream: true });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function readJson(response: Response): Promise<Record<string, unknown>> {
|
|
107
|
+
const text = await readCapped(response, MAX_RESPONSE_BYTES, true);
|
|
108
|
+
try {
|
|
109
|
+
const parsed = JSON.parse(text) as unknown;
|
|
110
|
+
if (parsed && typeof parsed === "object") return parsed as Record<string, unknown>;
|
|
111
|
+
} catch {
|
|
112
|
+
// fall through to the shared error below
|
|
113
|
+
}
|
|
114
|
+
throw new Error("PDF parser endpoint returned a non-JSON response");
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function errorBody(response: Response): Promise<string> {
|
|
118
|
+
try {
|
|
119
|
+
const text = await readCapped(response, MAX_ERROR_BODY_BYTES, false);
|
|
120
|
+
return text ? `: ${text}` : "";
|
|
121
|
+
} catch {
|
|
122
|
+
return "";
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function markdownResult(payload: Record<string, unknown>): EndpointPDFExtractResult {
|
|
127
|
+
// Strip NULs (leaked by PDF text layers with broken encodings) before the emptiness
|
|
128
|
+
// check: NUL-only output is an empty conversion and must fail so the chain falls back.
|
|
129
|
+
const markdown = typeof payload.markdown === "string" ? payload.markdown.replaceAll("\x00", "") : "";
|
|
130
|
+
if (markdown.trim().length === 0) {
|
|
131
|
+
const error = normalizeString(payload.error);
|
|
132
|
+
throw new Error(
|
|
133
|
+
error ? `PDF parser endpoint failed: ${error}` : "PDF parser endpoint returned no markdown",
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
return { markdown, pages: typeof payload.pages === "number" ? payload.pages : undefined };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* POST the PDF as multipart `file`. A `{ markdown }` answer completes at once; a
|
|
141
|
+
* `{ job_id }` answer is polled at `jobs/{id}` until `done`, `error`, or the deadline.
|
|
142
|
+
*/
|
|
143
|
+
export async function extractPDFViaEndpoint(
|
|
144
|
+
buffer: ArrayBuffer,
|
|
145
|
+
options: EndpointPDFExtractOptions,
|
|
146
|
+
): Promise<EndpointPDFExtractResult> {
|
|
147
|
+
options.signal?.throwIfAborted();
|
|
148
|
+
const endpointUrl = getEndpointUrl();
|
|
149
|
+
if (!endpointUrl) {
|
|
150
|
+
throw new Error("PDF endpoint extraction requires a configured pdf.endpointUrl");
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const ssrf = loadSsrfConfig();
|
|
154
|
+
// The parser URL is user-configured, like firecrawlBaseUrl, so loopback is allowed;
|
|
155
|
+
// LAN ranges still need ssrf.allowRanges, and every redirect hop is re-validated.
|
|
156
|
+
const guard = {
|
|
157
|
+
allowRanges: ssrf.allowRanges,
|
|
158
|
+
trustEnvProxy: ssrf.trustEnvProxy,
|
|
159
|
+
allowLoopback: isLoopbackHostname(new URL(endpointUrl).hostname),
|
|
160
|
+
...(options.lookup ? { lookup: options.lookup } : {}),
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
const engine = normalizeString(pdfSection().endpointEngine);
|
|
164
|
+
const form = new FormData();
|
|
165
|
+
form.append("file", new Blob([buffer], { type: "application/pdf" }), "document.pdf");
|
|
166
|
+
if (engine) form.append("engine", engine);
|
|
167
|
+
form.append("max_pages", String(options.maxPages));
|
|
168
|
+
|
|
169
|
+
const timeoutMs = options.timeoutMs ?? getEndpointTimeoutMs();
|
|
170
|
+
const deadline = Date.now() + timeoutMs;
|
|
171
|
+
const signal = options.signal;
|
|
172
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
173
|
+
const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
174
|
+
|
|
175
|
+
const response = await fetchRemoteUrl(
|
|
176
|
+
endpointUrl,
|
|
177
|
+
{ method: "POST", body: form, signal: combined },
|
|
178
|
+
guard,
|
|
179
|
+
);
|
|
180
|
+
if (!response.ok) {
|
|
181
|
+
throw new Error(
|
|
182
|
+
`PDF parser endpoint returned HTTP ${response.status}${await errorBody(response)}`,
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
let payload = await readJson(response);
|
|
187
|
+
const jobId = normalizeString(payload.job_id);
|
|
188
|
+
if (typeof payload.markdown === "string" || !jobId) {
|
|
189
|
+
return markdownResult(payload);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const jobsUrl = new URL(`jobs/${encodeURIComponent(jobId)}`, endpointUrl).toString();
|
|
193
|
+
for (let interval = 1_000; Date.now() < deadline; interval = Math.min(interval * 2, MAX_POLL_INTERVAL_MS)) {
|
|
194
|
+
await sleep(Math.min(interval, deadline - Date.now()), undefined, { signal });
|
|
195
|
+
|
|
196
|
+
const poll = await fetchRemoteUrl(jobsUrl, { signal: combined }, guard);
|
|
197
|
+
if (!poll.ok) {
|
|
198
|
+
throw new Error(
|
|
199
|
+
`PDF parser job status returned HTTP ${poll.status}${await errorBody(poll)}`,
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
payload = await readJson(poll);
|
|
203
|
+
const status = normalizeString(payload.status)?.toLowerCase();
|
|
204
|
+
if (status === "error" || status === "failed") {
|
|
205
|
+
const error = normalizeString(payload.error) ?? "unknown parser error";
|
|
206
|
+
throw new Error(`PDF parser endpoint job failed: ${error}`);
|
|
207
|
+
}
|
|
208
|
+
if (status === "done") {
|
|
209
|
+
let result = payload.result;
|
|
210
|
+
if (typeof result === "string") {
|
|
211
|
+
const raw = result;
|
|
212
|
+
try {
|
|
213
|
+
result = JSON.parse(raw);
|
|
214
|
+
} catch {
|
|
215
|
+
// Only a genuinely non-JSON body is raw markdown; a malformed JSON
|
|
216
|
+
// payload must fail so the chain falls back.
|
|
217
|
+
return { markdown: raw.replaceAll("\x00", "") };
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
if (result && typeof result === "object") return markdownResult(result as Record<string, unknown>);
|
|
221
|
+
throw new Error("PDF parser endpoint job completed without a result");
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
throw new Error("PDF parser endpoint job timed out");
|
|
225
|
+
}
|