@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,272 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { activityMonitor } from "./activity.ts";
|
|
3
|
+
import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
|
|
4
|
+
import type { ExtractedContent, ExtractOptions } from "./extract.ts";
|
|
5
|
+
import { validateRemoteUrl, type Lookup } from "./ssrf-protection.ts";
|
|
6
|
+
import { getWebSearchConfigPath, resolveProviderApiUrl } from "./utils.ts";
|
|
7
|
+
|
|
8
|
+
const CONFIG_PATH = getWebSearchConfigPath();
|
|
9
|
+
const BRIGHTDATA_REQUEST_URL = "https://api.brightdata.com/request";
|
|
10
|
+
const EXTRACT_TIMEOUT_MS = 60_000;
|
|
11
|
+
const DEFAULT_MAX_REDIRECTS = 5;
|
|
12
|
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
|
|
13
|
+
const ZONE_PATTERN = /^[a-z0-9_-]+$/i;
|
|
14
|
+
|
|
15
|
+
export interface BrightDataSsrfOptions {
|
|
16
|
+
allowRanges: string[];
|
|
17
|
+
trustEnvProxy: boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface BrightDataExtractOptions extends Pick<ExtractOptions, "timeoutMs" | "lookup"> {
|
|
21
|
+
ssrf?: BrightDataSsrfOptions;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface BrightDataConfig {
|
|
25
|
+
brightdataBaseUrl?: unknown;
|
|
26
|
+
brightdataApiKey?: unknown;
|
|
27
|
+
brightdataUnlockerZone?: unknown;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
let cachedConfig: BrightDataConfig | null = null;
|
|
31
|
+
|
|
32
|
+
// V8's JSON.parse message quotes a slice of the source text around the offending
|
|
33
|
+
// token — `JSON.parse('{"brightdataApiKey": bd-live-abc123}')` reports
|
|
34
|
+
// `Unexpected token 'b', ..."aApiKey": bd-live-ab"... is not valid JSON`. This
|
|
35
|
+
// file is where the API key lives, so echoing that message verbatim (which
|
|
36
|
+
// firecrawl.ts:50 and ssrf-protection.ts:39 both do) puts a fragment of the
|
|
37
|
+
// credential into an error string that extract.ts surfaces to the user. Only the
|
|
38
|
+
// position is safe to repeat; the snippet never is. The `Failed to parse ` prefix
|
|
39
|
+
// is preserved because extract.ts's isConfigParseError matches on it.
|
|
40
|
+
function parseFailureDetail(err: unknown): string {
|
|
41
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
42
|
+
const position = message.match(/at position \d+(?: \(line \d+ column \d+\))?/);
|
|
43
|
+
return position ? `invalid JSON ${position[0]}` : "invalid JSON";
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function loadConfig(): BrightDataConfig {
|
|
47
|
+
if (cachedConfig) return cachedConfig;
|
|
48
|
+
if (!existsSync(CONFIG_PATH)) {
|
|
49
|
+
cachedConfig = {};
|
|
50
|
+
return cachedConfig;
|
|
51
|
+
}
|
|
52
|
+
const raw = readFileSync(CONFIG_PATH, "utf8");
|
|
53
|
+
let parsed: unknown;
|
|
54
|
+
try {
|
|
55
|
+
parsed = JSON.parse(raw);
|
|
56
|
+
} catch (err) {
|
|
57
|
+
throw new Error(`Failed to parse ${CONFIG_PATH}: ${parseFailureDetail(err)}`);
|
|
58
|
+
}
|
|
59
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
60
|
+
throw new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);
|
|
61
|
+
}
|
|
62
|
+
cachedConfig = parsed as BrightDataConfig;
|
|
63
|
+
return cachedConfig;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function clearBrightDataUnlockerConfigCache(): void {
|
|
67
|
+
cachedConfig = null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function normalizeZone(value: unknown): string | null {
|
|
71
|
+
if (typeof value !== "string") return null;
|
|
72
|
+
const trimmed = value.trim();
|
|
73
|
+
if (!trimmed) return null;
|
|
74
|
+
return ZONE_PATTERN.test(trimmed) ? trimmed : null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
interface ZoneSetting {
|
|
78
|
+
raw: string;
|
|
79
|
+
label: string;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function zoneSetting(): ZoneSetting | null {
|
|
83
|
+
const fromEnv = process.env.BRIGHTDATA_UNLOCKER_ZONE;
|
|
84
|
+
if (typeof fromEnv === "string" && fromEnv.trim()) return { raw: fromEnv.trim(), label: "BRIGHTDATA_UNLOCKER_ZONE" };
|
|
85
|
+
const configured = loadConfig().brightdataUnlockerZone;
|
|
86
|
+
if (typeof configured === "string" && configured.trim()) return { raw: configured.trim(), label: `brightdataUnlockerZone in ${CONFIG_PATH}` };
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function getZone(): string | null {
|
|
91
|
+
const setting = zoneSetting();
|
|
92
|
+
return setting ? normalizeZone(setting.raw) : null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// A zone is never defaulted. Zones are per-account names bound to a product
|
|
96
|
+
// type, they are billed separately, and a guess is either an HTTP 400 or a
|
|
97
|
+
// charge against the wrong product.
|
|
98
|
+
function requireZone(): string {
|
|
99
|
+
const setting = zoneSetting();
|
|
100
|
+
const zone = setting ? normalizeZone(setting.raw) : null;
|
|
101
|
+
if (zone) return zone;
|
|
102
|
+
if (setting) {
|
|
103
|
+
throw new Error(
|
|
104
|
+
`Invalid Bright Data Unlocker zone: ${setting.label} must be a zone name of letters, digits, "-", or "_". ` +
|
|
105
|
+
"The zone must be of type \"unblocker\"; a SERP zone will not serve Web Unlocker requests.",
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
throw new Error(
|
|
109
|
+
"Bright Data Web Unlocker zone not configured. Either:\n" +
|
|
110
|
+
` 1. Set brightdataUnlockerZone in ${CONFIG_PATH}\n` +
|
|
111
|
+
" 2. Set BRIGHTDATA_UNLOCKER_ZONE environment variable\n" +
|
|
112
|
+
"The zone must be of type \"unblocker\"; a SERP zone will not serve Web Unlocker requests.",
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function getApiKey(signal?: AbortSignal): Promise<string> {
|
|
117
|
+
const apiKey = await resolveCredential({
|
|
118
|
+
provider: "Bright Data",
|
|
119
|
+
configuredValue: loadConfig().brightdataApiKey,
|
|
120
|
+
environmentValue: process.env.BRIGHTDATA_API_KEY,
|
|
121
|
+
signal,
|
|
122
|
+
});
|
|
123
|
+
if (!apiKey) {
|
|
124
|
+
throw new Error(
|
|
125
|
+
"Bright Data API key not found. Either:\n" +
|
|
126
|
+
` 1. Create ${CONFIG_PATH} with { "brightdataApiKey": "your-key" }\n` +
|
|
127
|
+
" 2. Set BRIGHTDATA_API_KEY environment variable\n" +
|
|
128
|
+
"Get a key at https://brightdata.com/cp/setting/users",
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
return apiKey;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function requestSignal(timeoutMs: number, signal?: AbortSignal): AbortSignal {
|
|
135
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
136
|
+
return signal ? AbortSignal.any([timeout, signal]) : timeout;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function errorMessage(err: unknown): string {
|
|
140
|
+
return err instanceof Error ? err.message : String(err);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function isAbortError(err: unknown): boolean {
|
|
144
|
+
return errorMessage(err).toLowerCase().includes("abort");
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function ssrfOptions(options?: BrightDataExtractOptions): { lookup?: Lookup; allowRanges: string[]; trustEnvProxy: boolean } {
|
|
148
|
+
return {
|
|
149
|
+
allowRanges: options?.ssrf?.allowRanges ?? [],
|
|
150
|
+
trustEnvProxy: options?.ssrf?.trustEnvProxy ?? false,
|
|
151
|
+
...(options?.lookup ? { lookup: options.lookup } : {}),
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function withoutSensitiveHeaders(headers: Record<string, string>): Record<string, string> {
|
|
156
|
+
const next = { ...headers };
|
|
157
|
+
delete next.Authorization;
|
|
158
|
+
delete next.authorization;
|
|
159
|
+
delete next.Cookie;
|
|
160
|
+
delete next.cookie;
|
|
161
|
+
delete next["X-API-Key"];
|
|
162
|
+
delete next["x-api-key"];
|
|
163
|
+
return next;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function fetchBrightDataApi(
|
|
167
|
+
url: string,
|
|
168
|
+
init: { method: string; headers: Record<string, string>; body: string; signal: AbortSignal },
|
|
169
|
+
options: BrightDataExtractOptions | undefined,
|
|
170
|
+
): Promise<Response> {
|
|
171
|
+
let current = await validateRemoteUrl(url, ssrfOptions(options));
|
|
172
|
+
let headers = init.headers;
|
|
173
|
+
// `redirect: "manual"` is what makes this loop exist: with the default "follow"
|
|
174
|
+
// the runtime resolves the chain itself, the final response is a 200, and the
|
|
175
|
+
// per-hop validateRemoteUrl / credential strip / hop cap below all become dead
|
|
176
|
+
// code. Tests assert the option is present on every hop for that reason.
|
|
177
|
+
//
|
|
178
|
+
// The loop is intentionally unbounded (`for (;;)`) with the cap enforced inside:
|
|
179
|
+
// a `redirects <= DEFAULT_MAX_REDIRECTS` header would make the post-loop
|
|
180
|
+
// statement provably unreachable, which is exactly the dead line firecrawl.ts
|
|
181
|
+
// carries at :186. Every exit is a `return` or a `throw` written here.
|
|
182
|
+
for (let redirects = 0; ; redirects++) {
|
|
183
|
+
const response = await fetch(current, { ...init, headers, redirect: "manual" });
|
|
184
|
+
if (!REDIRECT_STATUSES.has(response.status)) return response;
|
|
185
|
+
|
|
186
|
+
const location = response.headers.get("location");
|
|
187
|
+
if (!location) return response;
|
|
188
|
+
if (redirects === DEFAULT_MAX_REDIRECTS) throw new Error(`Too many redirects fetching ${current.toString()}`);
|
|
189
|
+
|
|
190
|
+
const next = await validateRemoteUrl(new URL(location, current), ssrfOptions(options));
|
|
191
|
+
if (next.origin !== current.origin) headers = withoutSensitiveHeaders(headers);
|
|
192
|
+
current = next;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function unlockerBody(url: string, zone: string): Record<string, unknown> {
|
|
197
|
+
return {
|
|
198
|
+
url,
|
|
199
|
+
zone,
|
|
200
|
+
format: "raw",
|
|
201
|
+
data_format: "markdown",
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function brightDataRequest(
|
|
206
|
+
url: string,
|
|
207
|
+
zone: string,
|
|
208
|
+
signal: AbortSignal | undefined,
|
|
209
|
+
options: BrightDataExtractOptions | undefined,
|
|
210
|
+
): Promise<string> {
|
|
211
|
+
const apiKey = await getApiKey(signal);
|
|
212
|
+
const headers: Record<string, string> = {
|
|
213
|
+
"Content-Type": "application/json",
|
|
214
|
+
Authorization: `Bearer ${apiKey}`,
|
|
215
|
+
};
|
|
216
|
+
const activityId = activityMonitor.logStart({ type: "fetch", url });
|
|
217
|
+
try {
|
|
218
|
+
const response = await fetchBrightDataApi(resolveProviderApiUrl("brightdata", BRIGHTDATA_REQUEST_URL, loadConfig().brightdataBaseUrl), {
|
|
219
|
+
method: "POST",
|
|
220
|
+
headers,
|
|
221
|
+
body: JSON.stringify(unlockerBody(url, zone)),
|
|
222
|
+
signal: requestSignal(options?.timeoutMs ?? EXTRACT_TIMEOUT_MS, signal),
|
|
223
|
+
}, options);
|
|
224
|
+
if (!response.ok) {
|
|
225
|
+
const errorText = await response.text().catch(() => "");
|
|
226
|
+
throw new Error(`Bright Data Web Unlocker error ${response.status}: ${redactCredential(errorText, apiKey).slice(0, 300)}`);
|
|
227
|
+
}
|
|
228
|
+
const text = await response.text();
|
|
229
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
230
|
+
return text;
|
|
231
|
+
} catch (err) {
|
|
232
|
+
const message = errorMessage(err);
|
|
233
|
+
const redactedMessage = redactCredential(message, apiKey);
|
|
234
|
+
if (isAbortError(err)) activityMonitor.logComplete(activityId, 0);
|
|
235
|
+
else activityMonitor.logError(activityId, redactedMessage);
|
|
236
|
+
if (redactedMessage === message) throw err;
|
|
237
|
+
const redactedError = new Error(redactedMessage);
|
|
238
|
+
if (err instanceof Error) redactedError.name = err.name;
|
|
239
|
+
throw redactedError;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function headingTitle(text: string): string {
|
|
244
|
+
const match = text.match(/^#{1,2}\s+(.+)/m);
|
|
245
|
+
if (!match) return "";
|
|
246
|
+
return match[1].replace(/\*+/g, "").trim();
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
export function isBrightDataUnlockerAvailable(): boolean {
|
|
250
|
+
if (getZone() === null) return false;
|
|
251
|
+
return hasCredentialSource({
|
|
252
|
+
provider: "Bright Data",
|
|
253
|
+
configuredValue: loadConfig().brightdataApiKey,
|
|
254
|
+
environmentValue: process.env.BRIGHTDATA_API_KEY,
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export async function extractWithBrightDataUnlocker(
|
|
259
|
+
url: string,
|
|
260
|
+
signal?: AbortSignal,
|
|
261
|
+
options?: BrightDataExtractOptions,
|
|
262
|
+
): Promise<ExtractedContent | null> {
|
|
263
|
+
const zone = requireZone();
|
|
264
|
+
await validateRemoteUrl(url, ssrfOptions(options));
|
|
265
|
+
const raw = await brightDataRequest(url, zone, signal, options);
|
|
266
|
+
// Bright Data bills a successful request whatever its length, so short
|
|
267
|
+
// content is returned rather than discarded: a paywall stub or consent page
|
|
268
|
+
// is a useful answer, and silently dropping it would hide the spend.
|
|
269
|
+
const content = raw.trim();
|
|
270
|
+
if (!content) return null;
|
|
271
|
+
return { url, title: headingTitle(content), content, error: null };
|
|
272
|
+
}
|
package/ceramic.ts
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { activityMonitor } from "./activity.ts";
|
|
3
|
+
import { normalizeDomain } from "./domain-filter-normalization.ts";
|
|
4
|
+
import type { SearchOptions, SearchResponse } from "./perplexity.ts";
|
|
5
|
+
import { formatSearchResultsAsAnswer } from "./search-answer-formatting.ts";
|
|
6
|
+
import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
|
|
7
|
+
import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
|
|
8
|
+
import { fetchWithCredentialRedirects, getWebSearchConfigPath, resolveProviderApiUrl } from "./utils.ts";
|
|
9
|
+
|
|
10
|
+
const CERAMIC_SEARCH_URL = "https://api.ceramic.ai/search";
|
|
11
|
+
const CONFIG_PATH = getWebSearchConfigPath();
|
|
12
|
+
const SEARCH_TIMEOUT_MS = 30_000;
|
|
13
|
+
const MAX_REQUEST_RESULTS = 20;
|
|
14
|
+
// Descriptions default to 3,000 characters; 1,000 is the smallest the API accepts. Results
|
|
15
|
+
// are trimmed further so ten of them, shown twice (answer and list), fit the inline budget.
|
|
16
|
+
const REQUEST_DESCRIPTION_CHARS = 1_000;
|
|
17
|
+
const MAX_SNIPPET_CHARS = 500;
|
|
18
|
+
|
|
19
|
+
interface WebSearchConfig {
|
|
20
|
+
ceramicBaseUrl?: unknown;
|
|
21
|
+
ceramicApiKey?: unknown;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface CeramicResult {
|
|
25
|
+
title?: unknown;
|
|
26
|
+
url?: unknown;
|
|
27
|
+
description?: unknown;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
let cachedConfig: WebSearchConfig | null = null;
|
|
31
|
+
|
|
32
|
+
function loadConfig(): WebSearchConfig {
|
|
33
|
+
if (cachedConfig) return cachedConfig;
|
|
34
|
+
if (!existsSync(CONFIG_PATH)) {
|
|
35
|
+
cachedConfig = {};
|
|
36
|
+
return cachedConfig;
|
|
37
|
+
}
|
|
38
|
+
const raw = readFileSync(CONFIG_PATH, "utf-8");
|
|
39
|
+
let parsed: unknown;
|
|
40
|
+
try {
|
|
41
|
+
parsed = JSON.parse(raw);
|
|
42
|
+
} catch (err) {
|
|
43
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
44
|
+
throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
|
|
45
|
+
}
|
|
46
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
47
|
+
throw new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);
|
|
48
|
+
}
|
|
49
|
+
cachedConfig = parsed as WebSearchConfig;
|
|
50
|
+
return cachedConfig;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function requireApiKey(signal?: AbortSignal): Promise<string> {
|
|
54
|
+
const apiKey = await resolveCredential({
|
|
55
|
+
provider: "Ceramic",
|
|
56
|
+
configuredValue: loadConfig().ceramicApiKey,
|
|
57
|
+
environmentValue: process.env.CERAMIC_API_KEY,
|
|
58
|
+
signal,
|
|
59
|
+
});
|
|
60
|
+
if (!apiKey) {
|
|
61
|
+
throw new Error(
|
|
62
|
+
"Ceramic API key not found. Either:\n" +
|
|
63
|
+
` 1. Create ${CONFIG_PATH} with { "ceramicApiKey": "your-key" }\n` +
|
|
64
|
+
" 2. Set CERAMIC_API_KEY environment variable\n" +
|
|
65
|
+
"Get a key at https://platform.ceramic.ai/keys",
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
return apiKey;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
interface DomainFilters {
|
|
72
|
+
include: string[];
|
|
73
|
+
exclude: string[];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function parseDomainFilter(domainFilter: string[] | undefined): DomainFilters {
|
|
77
|
+
const filters: DomainFilters = { include: [], exclude: [] };
|
|
78
|
+
for (const raw of domainFilter ?? []) {
|
|
79
|
+
const domain = normalizeDomain(raw);
|
|
80
|
+
if (!domain) continue;
|
|
81
|
+
const target = raw.trim().startsWith("-") ? filters.exclude : filters.include;
|
|
82
|
+
if (!target.includes(domain)) target.push(domain);
|
|
83
|
+
}
|
|
84
|
+
return filters;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function passesDomainFilters(url: URL, filters: DomainFilters): boolean {
|
|
88
|
+
if (filters.include.length === 0 && filters.exclude.length === 0) return true;
|
|
89
|
+
const hostname = url.hostname.toLowerCase();
|
|
90
|
+
const matches = (domain: string) => hostname === domain || hostname.endsWith(`.${domain}`);
|
|
91
|
+
if (filters.exclude.some(matches)) return false;
|
|
92
|
+
return filters.include.length === 0 || filters.include.some(matches);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Ceramic documents `site:`, uppercase `OR`, and parentheses, but not `-site:`, so
|
|
96
|
+
// excluded domains are only filtered out of the returned results.
|
|
97
|
+
function buildQuery(query: string, filters: DomainFilters): string {
|
|
98
|
+
if (filters.include.length === 0) return query;
|
|
99
|
+
const sites = filters.include.map(domain => `site:${domain}`);
|
|
100
|
+
return `${query} ${sites.length === 1 ? sites[0] : `(${sites.join(" OR ")})`}`;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function text(value: unknown): string {
|
|
104
|
+
return typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "";
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function errorMessage(err: unknown): string {
|
|
108
|
+
return err instanceof Error ? err.message : String(err);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function invalidResponse(message: string): Error {
|
|
112
|
+
return new Error(`Ceramic returned invalid response: ${message}`);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function parseResponse(value: unknown): CeramicResult[] {
|
|
116
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw invalidResponse("expected an object envelope");
|
|
117
|
+
const result = (value as Record<string, unknown>).result;
|
|
118
|
+
if (!result || typeof result !== "object" || Array.isArray(result)) throw invalidResponse("expected result object");
|
|
119
|
+
const results = (result as Record<string, unknown>).results;
|
|
120
|
+
if (!Array.isArray(results)) throw invalidResponse("expected result.results array");
|
|
121
|
+
return results as CeramicResult[];
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Ceramic errors are `{ title, status, detail, requestId, code }`; show the readable part.
|
|
125
|
+
function describeError(body: string): string {
|
|
126
|
+
try {
|
|
127
|
+
const parsed = JSON.parse(body) as Record<string, unknown>;
|
|
128
|
+
const parts = [text(parsed.title), text(parsed.detail)].filter(Boolean);
|
|
129
|
+
if (parts.length > 0) return parts.join(": ");
|
|
130
|
+
} catch {}
|
|
131
|
+
return body;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function isCeramicAvailable(): boolean {
|
|
135
|
+
return hasCredentialSource({ provider: "Ceramic", configuredValue: loadConfig().ceramicApiKey, environmentValue: process.env.CERAMIC_API_KEY });
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Ceramic has no date filter and returns no dates, so `recencyFilter` is not applied.
|
|
139
|
+
export async function searchWithCeramic(query: string, options: SearchOptions = {}): Promise<SearchResponse> {
|
|
140
|
+
const apiKey = await requireApiKey(options.signal);
|
|
141
|
+
const numResults = normalizeSearchResultCount(options.numResults);
|
|
142
|
+
const filters = parseDomainFilter(options.domainFilter);
|
|
143
|
+
// Results are reapplied to the domain filters locally, so leave a little headroom.
|
|
144
|
+
const hasDomainFilters = filters.include.length > 0 || filters.exclude.length > 0;
|
|
145
|
+
const body = {
|
|
146
|
+
query: buildQuery(query, filters),
|
|
147
|
+
maxResults: hasDomainFilters ? Math.min(MAX_REQUEST_RESULTS, numResults + 5) : numResults,
|
|
148
|
+
maxDescriptionLength: REQUEST_DESCRIPTION_CHARS,
|
|
149
|
+
};
|
|
150
|
+
const activityId = activityMonitor.logStart({ type: "api", query });
|
|
151
|
+
const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
|
|
152
|
+
let response: Response;
|
|
153
|
+
let entries: CeramicResult[];
|
|
154
|
+
try {
|
|
155
|
+
response = await fetchWithCredentialRedirects(resolveProviderApiUrl("ceramic", CERAMIC_SEARCH_URL, loadConfig().ceramicBaseUrl), {
|
|
156
|
+
method: "POST",
|
|
157
|
+
headers: {
|
|
158
|
+
Accept: "application/json",
|
|
159
|
+
"Content-Type": "application/json",
|
|
160
|
+
Authorization: `Bearer ${apiKey}`,
|
|
161
|
+
},
|
|
162
|
+
body: JSON.stringify(body),
|
|
163
|
+
signal: options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal,
|
|
164
|
+
}, ["Authorization"]);
|
|
165
|
+
if (!response.ok) {
|
|
166
|
+
const errorText = redactCredential(describeError(await response.text()), apiKey).slice(0, 300);
|
|
167
|
+
throw new Error(`Ceramic error ${response.status}: ${errorText}`);
|
|
168
|
+
}
|
|
169
|
+
let rawData: unknown;
|
|
170
|
+
try {
|
|
171
|
+
rawData = await response.json();
|
|
172
|
+
} catch (err) {
|
|
173
|
+
if (err instanceof Error && err.name === "TimeoutError") throw err;
|
|
174
|
+
throw new Error(`Ceramic returned invalid JSON: ${errorMessage(err)}`);
|
|
175
|
+
}
|
|
176
|
+
entries = parseResponse(rawData);
|
|
177
|
+
} catch (err) {
|
|
178
|
+
if (options.signal?.aborted) {
|
|
179
|
+
activityMonitor.logComplete(activityId, 0);
|
|
180
|
+
throw new Error("Aborted");
|
|
181
|
+
}
|
|
182
|
+
const message = errorMessage(err);
|
|
183
|
+
const providerTimeout = timeoutSignal.aborted || (err instanceof Error && err.name === "TimeoutError");
|
|
184
|
+
const outgoing = providerTimeout
|
|
185
|
+
? new Error(`Ceramic request timed out after ${Math.round(SEARCH_TIMEOUT_MS / 1000)}s`)
|
|
186
|
+
: (() => {
|
|
187
|
+
const redactedMessage = redactCredential(message, apiKey);
|
|
188
|
+
if (redactedMessage === message && err instanceof Error) return err;
|
|
189
|
+
const redactedError = new Error(redactedMessage);
|
|
190
|
+
if (err instanceof Error) redactedError.name = err.name;
|
|
191
|
+
return redactedError;
|
|
192
|
+
})();
|
|
193
|
+
activityMonitor.logError(activityId, redactCredential(errorMessage(outgoing), apiKey));
|
|
194
|
+
throw outgoing;
|
|
195
|
+
}
|
|
196
|
+
activityMonitor.logComplete(activityId, response.status);
|
|
197
|
+
const results: SearchResponse["results"] = [];
|
|
198
|
+
const seen = new Set<string>();
|
|
199
|
+
for (const entry of entries) {
|
|
200
|
+
if (!entry || typeof entry !== "object") continue;
|
|
201
|
+
if (typeof entry.url !== "string" || !entry.url) continue;
|
|
202
|
+
let resultUrl: URL;
|
|
203
|
+
try {
|
|
204
|
+
resultUrl = new URL(entry.url);
|
|
205
|
+
} catch {
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
if (resultUrl.protocol !== "http:" && resultUrl.protocol !== "https:") continue;
|
|
209
|
+
if (!passesDomainFilters(resultUrl, filters)) continue;
|
|
210
|
+
if (seen.has(resultUrl.href)) continue;
|
|
211
|
+
seen.add(resultUrl.href);
|
|
212
|
+
results.push({
|
|
213
|
+
title: text(entry.title) || `Source ${results.length + 1}`,
|
|
214
|
+
url: resultUrl.href,
|
|
215
|
+
snippet: text(entry.description).slice(0, MAX_SNIPPET_CHARS),
|
|
216
|
+
});
|
|
217
|
+
if (results.length >= numResults) break;
|
|
218
|
+
}
|
|
219
|
+
return { answer: formatSearchResultsAsAnswer(results), results };
|
|
220
|
+
}
|