@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,246 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { activityMonitor } from "./activity.ts";
|
|
3
|
+
import { normalizeDomain } from "./domain-filter-normalization.ts";
|
|
4
|
+
import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
|
|
5
|
+
import type { SearchOptions, SearchResponse } from "./perplexity.ts";
|
|
6
|
+
import { formatSearchResultsAsAnswer } from "./search-answer-formatting.ts";
|
|
7
|
+
import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
|
|
8
|
+
import { getWebSearchConfigPath, resolveProviderApiUrl, fetchWithCredentialRedirects } from "./utils.ts";
|
|
9
|
+
|
|
10
|
+
const SEARCHINFINITY_SEARCH_URL = "https://torchlight.byteintlapi.com/search_api/web_search";
|
|
11
|
+
const CONFIG_PATH = getWebSearchConfigPath();
|
|
12
|
+
// API Key authenticated requests time out server-side after 30 seconds.
|
|
13
|
+
const SEARCH_TIMEOUT_MS = 30_000;
|
|
14
|
+
|
|
15
|
+
interface WebSearchConfig {
|
|
16
|
+
searchinfinityBaseUrl?: unknown;
|
|
17
|
+
searchinfinityApiKey?: unknown;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface SearchinfinityWebResult {
|
|
21
|
+
Id?: string;
|
|
22
|
+
SortId?: number;
|
|
23
|
+
Title?: string | null;
|
|
24
|
+
SiteName?: string | null;
|
|
25
|
+
Url?: string | null;
|
|
26
|
+
Snippet?: string | null;
|
|
27
|
+
Summary?: string | null;
|
|
28
|
+
PublishTime?: string | null;
|
|
29
|
+
LogoUrl?: string | null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface SearchinfinitySearchResponse {
|
|
33
|
+
ResponseMetadata?: {
|
|
34
|
+
RequestId?: string;
|
|
35
|
+
Error?: {
|
|
36
|
+
CodeN?: number;
|
|
37
|
+
Code?: string;
|
|
38
|
+
Message?: string;
|
|
39
|
+
} | null;
|
|
40
|
+
};
|
|
41
|
+
Result?: {
|
|
42
|
+
ResultCount?: number;
|
|
43
|
+
WebResults?: SearchinfinityWebResult[];
|
|
44
|
+
SearchContext?: {
|
|
45
|
+
OriginQuery?: string;
|
|
46
|
+
SearchType?: string;
|
|
47
|
+
};
|
|
48
|
+
TimeCost?: number;
|
|
49
|
+
LogId?: string;
|
|
50
|
+
} | null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
interface SearchinfinitySearchOptions extends SearchOptions {
|
|
54
|
+
includeContent?: boolean;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
let cachedConfig: WebSearchConfig | null = null;
|
|
58
|
+
|
|
59
|
+
function loadConfig(): WebSearchConfig {
|
|
60
|
+
if (cachedConfig) return cachedConfig;
|
|
61
|
+
if (!existsSync(CONFIG_PATH)) {
|
|
62
|
+
cachedConfig = {};
|
|
63
|
+
return cachedConfig;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const raw = readFileSync(CONFIG_PATH, "utf-8");
|
|
67
|
+
let parsed: unknown;
|
|
68
|
+
try {
|
|
69
|
+
parsed = JSON.parse(raw);
|
|
70
|
+
} catch (err) {
|
|
71
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
72
|
+
throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
|
|
73
|
+
}
|
|
74
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
75
|
+
throw new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);
|
|
76
|
+
}
|
|
77
|
+
cachedConfig = parsed as WebSearchConfig;
|
|
78
|
+
return cachedConfig;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function getApiKey(signal?: AbortSignal): Promise<string> {
|
|
82
|
+
const key = await resolveCredential({
|
|
83
|
+
provider: "Searchinfinity",
|
|
84
|
+
configuredValue: loadConfig().searchinfinityApiKey,
|
|
85
|
+
environmentValue: process.env.SEARCHINFINITY_API_KEY,
|
|
86
|
+
signal,
|
|
87
|
+
});
|
|
88
|
+
if (!key) {
|
|
89
|
+
throw new Error(
|
|
90
|
+
"Searchinfinity API key not found. Either:\n" +
|
|
91
|
+
` 1. Create ${CONFIG_PATH} with { "searchinfinityApiKey": "your-key" }\n` +
|
|
92
|
+
" 2. Set SEARCHINFINITY_API_KEY environment variable\n" +
|
|
93
|
+
"Create a key at https://console.byteplus.com/search-infinity/api-key",
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
return key;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function isSearchinfinityAvailable(): boolean {
|
|
100
|
+
return hasCredentialSource({
|
|
101
|
+
provider: "Searchinfinity",
|
|
102
|
+
configuredValue: loadConfig().searchinfinityApiKey,
|
|
103
|
+
environmentValue: process.env.SEARCHINFINITY_API_KEY,
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function errorMessage(err: unknown): string {
|
|
108
|
+
return err instanceof Error ? err.message : String(err);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function requestSignal(signal: AbortSignal | undefined, timeoutMs: number): AbortSignal {
|
|
112
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
113
|
+
return signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function mapRecencyFilter(recency: SearchOptions["recencyFilter"]): string | undefined {
|
|
117
|
+
if (recency === "day") return "OneDay";
|
|
118
|
+
if (recency === "week") return "OneWeek";
|
|
119
|
+
if (recency === "month") return "OneMonth";
|
|
120
|
+
if (recency === "year") return "OneYear";
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function buildSearchBody(query: string, options: SearchinfinitySearchOptions): Record<string, unknown> {
|
|
125
|
+
const includeSites: string[] = [];
|
|
126
|
+
const blockHosts: string[] = [];
|
|
127
|
+
for (const raw of options.domainFilter ?? []) {
|
|
128
|
+
const domain = normalizeDomain(raw);
|
|
129
|
+
if (!domain) continue;
|
|
130
|
+
const target = raw.trim().startsWith("-") ? blockHosts : includeSites;
|
|
131
|
+
if (target.length < 5 && !target.includes(domain)) target.push(domain);
|
|
132
|
+
}
|
|
133
|
+
const filter: Record<string, unknown> = {};
|
|
134
|
+
if (includeSites.length > 0) filter.Sites = includeSites.join("|");
|
|
135
|
+
if (blockHosts.length > 0) filter.BlockHosts = blockHosts.join("|");
|
|
136
|
+
|
|
137
|
+
const timeRange = mapRecencyFilter(options.recencyFilter);
|
|
138
|
+
return {
|
|
139
|
+
Query: query,
|
|
140
|
+
Count: normalizeSearchResultCount(options.numResults),
|
|
141
|
+
...(Object.keys(filter).length > 0 ? { Filter: filter } : {}),
|
|
142
|
+
...(timeRange ? { TimeRange: timeRange } : {}),
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Map Searchinfinity business error codes to the closest HTTP semantics so
|
|
147
|
+
// error classification (auth/quota/invalid-request/transient) keeps working.
|
|
148
|
+
// CodeN carries the numeric code (e.g. 700901); Code may be a slug (e.g.
|
|
149
|
+
// "invalid_api_key"), so match both.
|
|
150
|
+
function businessErrorStatus(codeN: number | undefined, code: string, message: string): number | undefined {
|
|
151
|
+
if (codeN === 700901 || code === "invalid_api_key") return 401;
|
|
152
|
+
if (codeN === 700429 || code === "700429") return 429;
|
|
153
|
+
if (codeN === 10400 || code === "10400") return 400;
|
|
154
|
+
if (codeN === 10500 || code === "10500") return 500;
|
|
155
|
+
if (codeN === 10403 || code === "10403") return /quota|exhaust/i.test(message) ? 429 : 403;
|
|
156
|
+
return undefined;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function searchinfinityJsonRequest(
|
|
160
|
+
apiKey: string,
|
|
161
|
+
body: Record<string, unknown>,
|
|
162
|
+
signal?: AbortSignal,
|
|
163
|
+
): Promise<SearchinfinitySearchResponse> {
|
|
164
|
+
let response: Response;
|
|
165
|
+
try {
|
|
166
|
+
response = await fetchWithCredentialRedirects(resolveProviderApiUrl("searchinfinity", SEARCHINFINITY_SEARCH_URL, loadConfig().searchinfinityBaseUrl), {
|
|
167
|
+
method: "POST",
|
|
168
|
+
headers: {
|
|
169
|
+
Authorization: `Bearer ${apiKey}`,
|
|
170
|
+
"Content-Type": "application/json",
|
|
171
|
+
},
|
|
172
|
+
body: JSON.stringify(body),
|
|
173
|
+
signal: requestSignal(signal, SEARCH_TIMEOUT_MS),
|
|
174
|
+
}, ["Authorization"]);
|
|
175
|
+
} catch (err) {
|
|
176
|
+
const message = errorMessage(err);
|
|
177
|
+
const redactedMessage = redactCredential(message, apiKey);
|
|
178
|
+
if (redactedMessage === message) throw err;
|
|
179
|
+
const redactedError = new Error(redactedMessage);
|
|
180
|
+
if (err instanceof Error) redactedError.name = err.name;
|
|
181
|
+
throw redactedError;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const raw = await response.text();
|
|
185
|
+
if (!response.ok) {
|
|
186
|
+
throw new Error(`Searchinfinity Search API error ${response.status}: ${redactCredential(raw, apiKey).slice(0, 300)}`);
|
|
187
|
+
}
|
|
188
|
+
let data: SearchinfinitySearchResponse;
|
|
189
|
+
try {
|
|
190
|
+
data = JSON.parse(raw) as SearchinfinitySearchResponse;
|
|
191
|
+
} catch (err) {
|
|
192
|
+
throw new Error(`Searchinfinity Search API returned invalid JSON: ${errorMessage(err)}`);
|
|
193
|
+
}
|
|
194
|
+
const businessError = data.ResponseMetadata?.Error;
|
|
195
|
+
if (businessError && (businessError.Code || businessError.Message)) {
|
|
196
|
+
const code = typeof businessError.Code === "string" && businessError.Code ? businessError.Code : "unknown";
|
|
197
|
+
const message = typeof businessError.Message === "string" && businessError.Message ? businessError.Message : "unknown error";
|
|
198
|
+
const status = businessErrorStatus(businessError.CodeN, code, message);
|
|
199
|
+
const codeLabel = typeof businessError.CodeN === "number" ? `${businessError.CodeN} ${code}` : code;
|
|
200
|
+
throw new Error(
|
|
201
|
+
`Searchinfinity Search API error ${status ?? "unknown"}: ${message} (code ${codeLabel})`,
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
return data;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function mapSearchResults(results: SearchinfinityWebResult[] | undefined): SearchResponse["results"] {
|
|
208
|
+
if (!Array.isArray(results)) {
|
|
209
|
+
throw new Error("Searchinfinity Search API returned an unexpected response shape");
|
|
210
|
+
}
|
|
211
|
+
return results.flatMap((item) => {
|
|
212
|
+
if (!item || typeof item.Url !== "string" || item.Url.trim().length === 0) return [];
|
|
213
|
+
const url = item.Url.trim();
|
|
214
|
+
const summary = typeof item.Summary === "string" ? item.Summary.replace(/\s+/g, " ").trim() : "";
|
|
215
|
+
const snippet = typeof item.Snippet === "string" ? item.Snippet.replace(/\s+/g, " ").trim() : "";
|
|
216
|
+
return [{
|
|
217
|
+
title: typeof item.Title === "string" && item.Title.trim() ? item.Title.trim() : url,
|
|
218
|
+
url,
|
|
219
|
+
snippet: summary || snippet,
|
|
220
|
+
}];
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export async function searchWithSearchinfinity(
|
|
225
|
+
query: string,
|
|
226
|
+
options: SearchinfinitySearchOptions = {},
|
|
227
|
+
): Promise<SearchResponse> {
|
|
228
|
+
const apiKey = await getApiKey(options.signal);
|
|
229
|
+
const activityId = activityMonitor.logStart({ type: "api", query });
|
|
230
|
+
try {
|
|
231
|
+
const data = await searchinfinityJsonRequest(apiKey, buildSearchBody(query, options), options.signal);
|
|
232
|
+
const results = mapSearchResults(data.Result?.WebResults);
|
|
233
|
+
const response: SearchResponse = { answer: formatSearchResultsAsAnswer(results), results };
|
|
234
|
+
activityMonitor.logComplete(activityId, 200);
|
|
235
|
+
return response;
|
|
236
|
+
} catch (err) {
|
|
237
|
+
const message = errorMessage(err);
|
|
238
|
+
const redactedMessage = redactCredential(message, apiKey);
|
|
239
|
+
if (redactedMessage.toLowerCase().includes("abort")) activityMonitor.logComplete(activityId, 0);
|
|
240
|
+
else activityMonitor.logError(activityId, redactedMessage);
|
|
241
|
+
if (redactedMessage === message) throw err;
|
|
242
|
+
const redactedError = new Error(redactedMessage);
|
|
243
|
+
if (err instanceof Error) redactedError.name = err.name;
|
|
244
|
+
throw redactedError;
|
|
245
|
+
}
|
|
246
|
+
}
|
package/searxng.ts
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { activityMonitor } from "./activity.ts";
|
|
3
|
+
import { normalizeDomain } from "./domain-filter-normalization.ts";
|
|
4
|
+
import { fetchRemoteUrl, loadSsrfConfig } from "./ssrf-protection.ts";
|
|
5
|
+
import type { SearchOptions, SearchResult, SearchResponse } from "./perplexity.ts";
|
|
6
|
+
import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
|
|
7
|
+
import { getWebSearchConfigPath, isLoopbackHostname } from "./utils.ts";
|
|
8
|
+
|
|
9
|
+
const CONFIG_PATH = getWebSearchConfigPath();
|
|
10
|
+
const SEARCH_TIMEOUT_MS = 30_000;
|
|
11
|
+
|
|
12
|
+
interface WebSearchConfig {
|
|
13
|
+
searxngBaseUrl?: unknown;
|
|
14
|
+
searxngHeaders?: unknown;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
interface NormalizedDomainFilters {
|
|
18
|
+
allowed: string[];
|
|
19
|
+
blocked: string[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface SearXNGResult {
|
|
23
|
+
title?: string;
|
|
24
|
+
url?: string;
|
|
25
|
+
content?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface SearXNGResponse {
|
|
29
|
+
results?: SearXNGResult[];
|
|
30
|
+
answers?: string[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
let cachedConfig: WebSearchConfig | null = null;
|
|
34
|
+
|
|
35
|
+
function loadConfig(): WebSearchConfig {
|
|
36
|
+
if (cachedConfig) return cachedConfig;
|
|
37
|
+
if (!existsSync(CONFIG_PATH)) {
|
|
38
|
+
cachedConfig = {};
|
|
39
|
+
return cachedConfig;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const raw = readFileSync(CONFIG_PATH, "utf-8");
|
|
43
|
+
try {
|
|
44
|
+
cachedConfig = JSON.parse(raw) as WebSearchConfig;
|
|
45
|
+
return cachedConfig;
|
|
46
|
+
} catch (err) {
|
|
47
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
48
|
+
throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function normalizeBaseUrl(value: unknown): string | null {
|
|
53
|
+
if (typeof value !== "string") return null;
|
|
54
|
+
const trimmed = value.trim();
|
|
55
|
+
if (!trimmed) return null;
|
|
56
|
+
try {
|
|
57
|
+
const url = new URL(trimmed);
|
|
58
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
|
|
59
|
+
if (url.username || url.password) return null;
|
|
60
|
+
url.pathname = url.pathname.replace(/\/+$/, "");
|
|
61
|
+
url.search = "";
|
|
62
|
+
url.hash = "";
|
|
63
|
+
return url.toString().replace(/\/+$/, "");
|
|
64
|
+
} catch {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function getBaseUrl(): string | null {
|
|
70
|
+
const configured = process.env.SEARXNG_BASE_URL;
|
|
71
|
+
return configured !== undefined
|
|
72
|
+
? normalizeBaseUrl(configured)
|
|
73
|
+
: normalizeBaseUrl(loadConfig().searxngBaseUrl);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function isValidHeaderValue(value: string): boolean {
|
|
77
|
+
try {
|
|
78
|
+
new Headers({ "x-pi-web-access-validation": value });
|
|
79
|
+
return true;
|
|
80
|
+
} catch {
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function normalizeHeaders(value: unknown): Record<string, string> {
|
|
86
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
|
87
|
+
const headers: Record<string, string> = {};
|
|
88
|
+
for (const [key, headerValue] of Object.entries(value as Record<string, unknown>)) {
|
|
89
|
+
if (typeof headerValue !== "string") continue;
|
|
90
|
+
const name = key.trim();
|
|
91
|
+
// RFC 7230 token chars only — reject empty or malformed header names.
|
|
92
|
+
if (!name || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) continue;
|
|
93
|
+
if (!isValidHeaderValue(headerValue)) continue;
|
|
94
|
+
headers[name] = headerValue;
|
|
95
|
+
}
|
|
96
|
+
return headers;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function getConfiguredHeaders(): Record<string, string> {
|
|
100
|
+
return normalizeHeaders(loadConfig().searxngHeaders);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function mergeDefaultHeaders(configured: Record<string, string>): Record<string, string> {
|
|
104
|
+
const headers: Record<string, string> = { Accept: "application/json" };
|
|
105
|
+
for (const [name, value] of Object.entries(configured)) {
|
|
106
|
+
for (const existing of Object.keys(headers)) {
|
|
107
|
+
if (existing.toLowerCase() === name.toLowerCase()) delete headers[existing];
|
|
108
|
+
}
|
|
109
|
+
headers[name] = value;
|
|
110
|
+
}
|
|
111
|
+
return headers;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function requireBaseUrl(): string {
|
|
115
|
+
const baseUrl = getBaseUrl();
|
|
116
|
+
if (!baseUrl) {
|
|
117
|
+
throw new Error(
|
|
118
|
+
"SearXNG base URL is invalid or missing. Either:\n" +
|
|
119
|
+
` 1. Create ${CONFIG_PATH} with { "searxngBaseUrl": "https://search.example.com" }\n` +
|
|
120
|
+
" 2. Set SEARXNG_BASE_URL to an HTTP(S) URL",
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
return baseUrl;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function normalizeDomainFilters(domainFilter: string[] | undefined): NormalizedDomainFilters {
|
|
127
|
+
const filters: NormalizedDomainFilters = { allowed: [], blocked: [] };
|
|
128
|
+
for (const raw of domainFilter ?? []) {
|
|
129
|
+
const domain = normalizeDomain(raw);
|
|
130
|
+
if (!domain) continue;
|
|
131
|
+
const target = raw.trim().startsWith("-") ? filters.blocked : filters.allowed;
|
|
132
|
+
if (!target.includes(domain)) target.push(domain);
|
|
133
|
+
}
|
|
134
|
+
return filters;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function buildSearXNGQuery(query: string, filters: NormalizedDomainFilters): string {
|
|
138
|
+
const parts = [query];
|
|
139
|
+
if (filters.allowed.length === 1) {
|
|
140
|
+
parts.push(`site:${filters.allowed[0]}`);
|
|
141
|
+
} else if (filters.allowed.length > 1) {
|
|
142
|
+
parts.push(filters.allowed.map(domain => `site:${domain}`).join(" OR "));
|
|
143
|
+
}
|
|
144
|
+
for (const domain of filters.blocked) parts.push(`-site:${domain}`);
|
|
145
|
+
return parts.join(" ");
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function hostMatchesDomain(hostname: string, domain: string): boolean {
|
|
149
|
+
return hostname === domain || hostname.endsWith(`.${domain}`);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function matchesDomainFilters(url: string, filters: NormalizedDomainFilters): boolean {
|
|
153
|
+
if (filters.allowed.length === 0 && filters.blocked.length === 0) return true;
|
|
154
|
+
let hostname: string;
|
|
155
|
+
try {
|
|
156
|
+
hostname = new URL(url).hostname.toLowerCase();
|
|
157
|
+
} catch {
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
if (filters.allowed.length > 0 && !filters.allowed.some(domain => hostMatchesDomain(hostname, domain))) return false;
|
|
161
|
+
return !filters.blocked.some(domain => hostMatchesDomain(hostname, domain));
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function mapTimeRange(recencyFilter: SearchOptions["recencyFilter"]): string | null {
|
|
165
|
+
return recencyFilter === "day" || recencyFilter === "week" || recencyFilter === "month" || recencyFilter === "year"
|
|
166
|
+
? recencyFilter
|
|
167
|
+
: null;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function isSearXNGAvailable(): boolean {
|
|
171
|
+
const baseUrl = getBaseUrl();
|
|
172
|
+
if (baseUrl === null) return false;
|
|
173
|
+
loadSsrfConfig();
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export async function searchWithSearXNG(query: string, options: SearchOptions = {}): Promise<SearchResponse> {
|
|
178
|
+
const baseUrl = requireBaseUrl();
|
|
179
|
+
const numResults = normalizeSearchResultCount(options.numResults);
|
|
180
|
+
const filters = normalizeDomainFilters(options.domainFilter);
|
|
181
|
+
const searchQuery = buildSearXNGQuery(query, filters);
|
|
182
|
+
const url = new URL(`${baseUrl}/search`);
|
|
183
|
+
url.searchParams.set("q", searchQuery);
|
|
184
|
+
url.searchParams.set("format", "json");
|
|
185
|
+
const timeRange = mapTimeRange(options.recencyFilter);
|
|
186
|
+
if (timeRange) url.searchParams.set("time_range", timeRange);
|
|
187
|
+
const activityId = activityMonitor.logStart({ type: "api", query: searchQuery });
|
|
188
|
+
|
|
189
|
+
try {
|
|
190
|
+
const headers = mergeDefaultHeaders(getConfiguredHeaders());
|
|
191
|
+
const response = await fetchRemoteUrl(url, {
|
|
192
|
+
method: "GET",
|
|
193
|
+
headers,
|
|
194
|
+
signal: options.signal
|
|
195
|
+
? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS), options.signal])
|
|
196
|
+
: AbortSignal.timeout(SEARCH_TIMEOUT_MS),
|
|
197
|
+
}, {
|
|
198
|
+
...loadSsrfConfig(),
|
|
199
|
+
allowLoopback: isLoopbackHostname(url.hostname),
|
|
200
|
+
onRedirect: ({ from, to, init }) => from.origin === to.origin ? init : { ...init, headers: { Accept: "application/json" } },
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
if (!response.ok) {
|
|
204
|
+
activityMonitor.logError(activityId, `HTTP ${response.status}`);
|
|
205
|
+
const errorText = await response.text();
|
|
206
|
+
throw new Error(`SearXNG search error ${response.status}: ${errorText.slice(0, 300)}`);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
let data: SearXNGResponse;
|
|
210
|
+
try {
|
|
211
|
+
data = await response.json() as SearXNGResponse;
|
|
212
|
+
} catch (err) {
|
|
213
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
214
|
+
throw new Error(`SearXNG returned invalid JSON: ${message}`);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
218
|
+
const results: SearchResult[] = [];
|
|
219
|
+
for (const item of data.results ?? []) {
|
|
220
|
+
if (!item.url || !matchesDomainFilters(item.url, filters)) continue;
|
|
221
|
+
results.push({ title: item.title || item.url, url: item.url, snippet: item.content || "" });
|
|
222
|
+
if (results.length >= numResults) break;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const answerParts = (data.answers ?? []).filter((answer): answer is string => typeof answer === "string" && answer.trim().length > 0).map(answer => answer.trim());
|
|
226
|
+
answerParts.push(...results.map(result => result.snippet
|
|
227
|
+
? `${result.snippet}\nSource: ${result.title} (${result.url})`
|
|
228
|
+
: `Source: ${result.title} (${result.url})`));
|
|
229
|
+
return { answer: answerParts.join("\n\n"), results };
|
|
230
|
+
} catch (err) {
|
|
231
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
232
|
+
if (message.toLowerCase().includes("abort")) activityMonitor.logComplete(activityId, 0);
|
|
233
|
+
else activityMonitor.logError(activityId, message);
|
|
234
|
+
throw err;
|
|
235
|
+
}
|
|
236
|
+
}
|