@abhishek944/pi-web-access 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (201) hide show
  1. package/ASTACK.md +23 -0
  2. package/CHANGELOG.md +1289 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1215 -2
  5. package/SECURITY.md +5 -0
  6. package/abortable.ts +17 -0
  7. package/activity.ts +101 -0
  8. package/anysearch.ts +188 -0
  9. package/auth-fetch.ts +152 -0
  10. package/baizhi.ts +124 -0
  11. package/banner.png +0 -0
  12. package/bocha.ts +203 -0
  13. package/brave-rate-limit.ts +176 -0
  14. package/brave.ts +247 -0
  15. package/brightdata-unlocker.ts +272 -0
  16. package/ceramic.ts +220 -0
  17. package/chrome-cookies.ts +752 -0
  18. package/cloudflare-search.ts +237 -0
  19. package/content-find.ts +255 -0
  20. package/crawl4ai.ts +196 -0
  21. package/credential-source.ts +242 -0
  22. package/curator-page.ts +3607 -0
  23. package/curator-run.ts +45 -0
  24. package/curator-server.ts +761 -0
  25. package/custom-search.ts +226 -0
  26. package/data-uri-sanitize.ts +406 -0
  27. package/datalab-pdf-extract.ts +568 -0
  28. package/declared-web-links.ts +173 -0
  29. package/deepseek.ts +377 -0
  30. package/degoog.ts +323 -0
  31. package/dist/index.js +28286 -0
  32. package/dist/mcp-cli.js +29186 -0
  33. package/dist/pi-mcp.js +20855 -0
  34. package/dist/types/abortable.d.ts +2 -0
  35. package/dist/types/activity.d.ts +33 -0
  36. package/dist/types/anysearch.d.ts +7 -0
  37. package/dist/types/auth-fetch.d.ts +14 -0
  38. package/dist/types/baizhi.d.ts +3 -0
  39. package/dist/types/bocha.d.ts +3 -0
  40. package/dist/types/brave-rate-limit.d.ts +35 -0
  41. package/dist/types/brave.d.ts +3 -0
  42. package/dist/types/brightdata-unlocker.d.ts +11 -0
  43. package/dist/types/ceramic.d.ts +3 -0
  44. package/dist/types/chrome-cookies.d.ts +44 -0
  45. package/dist/types/cloudflare-search.d.ts +4 -0
  46. package/dist/types/content-find.d.ts +10 -0
  47. package/dist/types/crawl4ai.d.ts +8 -0
  48. package/dist/types/credential-source.d.ts +29 -0
  49. package/dist/types/curator-page.d.ts +5 -0
  50. package/dist/types/curator-run.d.ts +10 -0
  51. package/dist/types/curator-server.d.ts +72 -0
  52. package/dist/types/custom-search.d.ts +22 -0
  53. package/dist/types/data-uri-sanitize.d.ts +20 -0
  54. package/dist/types/datalab-pdf-extract.d.ts +59 -0
  55. package/dist/types/declared-web-links.d.ts +7 -0
  56. package/dist/types/deepseek.d.ts +13 -0
  57. package/dist/types/degoog.d.ts +3 -0
  58. package/dist/types/domain-filter-normalization.d.ts +9 -0
  59. package/dist/types/duckduckgo-rate-limit.d.ts +52 -0
  60. package/dist/types/duckduckgo.d.ts +6 -0
  61. package/dist/types/endpoint-pdf-extract.d.ts +22 -0
  62. package/dist/types/exa.d.ts +17 -0
  63. package/dist/types/extract.d.ts +70 -0
  64. package/dist/types/feature-config.d.ts +2 -0
  65. package/dist/types/fetch-params.d.ts +39 -0
  66. package/dist/types/field-extract.d.ts +37 -0
  67. package/dist/types/firecrawl.d.ts +18 -0
  68. package/dist/types/gemini-adc.d.ts +9 -0
  69. package/dist/types/gemini-api.d.ts +37 -0
  70. package/dist/types/gemini-pdf-extract.d.ts +8 -0
  71. package/dist/types/gemini-search.d.ts +76 -0
  72. package/dist/types/gemini-url-context.d.ts +3 -0
  73. package/dist/types/gemini-web-config.d.ts +25 -0
  74. package/dist/types/gemini-web.d.ts +31 -0
  75. package/dist/types/github-api.d.ts +6 -0
  76. package/dist/types/github-extract.d.ts +19 -0
  77. package/dist/types/github-issue-pr.d.ts +28 -0
  78. package/dist/types/index.d.ts +53 -0
  79. package/dist/types/jina-search.d.ts +7 -0
  80. package/dist/types/kagi.d.ts +14 -0
  81. package/dist/types/keenable.d.ts +3 -0
  82. package/dist/types/kimi-search.d.ts +4 -0
  83. package/dist/types/linkup.d.ts +5 -0
  84. package/dist/types/mcp-cli.d.ts +2 -0
  85. package/dist/types/mcp-server.d.ts +10 -0
  86. package/dist/types/mcp-tool-definitions.d.ts +16 -0
  87. package/dist/types/mistral-search.d.ts +3 -0
  88. package/dist/types/ninerouter.d.ts +3 -0
  89. package/dist/types/offtopic-judge.d.ts +26 -0
  90. package/dist/types/ollama.d.ts +14 -0
  91. package/dist/types/openai-search.d.ts +23 -0
  92. package/dist/types/page-query.d.ts +22 -0
  93. package/dist/types/parallel-mcp.d.ts +10 -0
  94. package/dist/types/parallel.d.ts +13 -0
  95. package/dist/types/pdf-extract.d.ts +44 -0
  96. package/dist/types/perplexity.d.ts +26 -0
  97. package/dist/types/pi-mcp.d.ts +56 -0
  98. package/dist/types/pi-session-results.d.ts +8 -0
  99. package/dist/types/querit.d.ts +9 -0
  100. package/dist/types/query-rewrite.d.ts +2 -0
  101. package/dist/types/render-search-error.d.ts +56 -0
  102. package/dist/types/retrieval-only.d.ts +78 -0
  103. package/dist/types/rsc-extract.d.ts +11 -0
  104. package/dist/types/search-answer-formatting.d.ts +7 -0
  105. package/dist/types/search-result-count-normalization.d.ts +1 -0
  106. package/dist/types/searchinfinity.d.ts +7 -0
  107. package/dist/types/searxng.d.ts +3 -0
  108. package/dist/types/source-check.d.ts +102 -0
  109. package/dist/types/ssrf-protection.d.ts +66 -0
  110. package/dist/types/storage.d.ts +69 -0
  111. package/dist/types/summary-model-scope.d.ts +33 -0
  112. package/dist/types/summary-review.d.ts +30 -0
  113. package/dist/types/tabstack.d.ts +5 -0
  114. package/dist/types/tavily.d.ts +7 -0
  115. package/dist/types/tinyfish.d.ts +10 -0
  116. package/dist/types/tool-activation.d.ts +7 -0
  117. package/dist/types/tool-arguments.d.ts +1 -0
  118. package/dist/types/upgrade-notice.d.ts +6 -0
  119. package/dist/types/utils.d.ts +55 -0
  120. package/dist/types/valyu.d.ts +5 -0
  121. package/dist/types/video-extract.d.ts +15 -0
  122. package/dist/types/web-tool-contract.d.ts +98 -0
  123. package/dist/types/web-tool-core.d.ts +227 -0
  124. package/dist/types/xai-search.d.ts +12 -0
  125. package/dist/types/you.d.ts +3 -0
  126. package/dist/types/youtube-extract.d.ts +29 -0
  127. package/dist/types/zai.d.ts +3 -0
  128. package/docs/pi-mcp.md +41 -0
  129. package/domain-filter-normalization.ts +44 -0
  130. package/duckduckgo-rate-limit.ts +205 -0
  131. package/duckduckgo.ts +123 -0
  132. package/endpoint-pdf-extract.ts +225 -0
  133. package/exa.ts +620 -0
  134. package/extract.ts +1721 -0
  135. package/feature-config.ts +29 -0
  136. package/fetch-params.ts +147 -0
  137. package/field-extract.ts +347 -0
  138. package/firecrawl.ts +476 -0
  139. package/gemini-adc.ts +345 -0
  140. package/gemini-api.ts +368 -0
  141. package/gemini-pdf-extract.ts +108 -0
  142. package/gemini-search.ts +1162 -0
  143. package/gemini-url-context.ts +128 -0
  144. package/gemini-web-config.ts +131 -0
  145. package/gemini-web.ts +527 -0
  146. package/github-api.ts +197 -0
  147. package/github-extract.ts +1064 -0
  148. package/github-issue-pr.ts +717 -0
  149. package/index.ts +2819 -0
  150. package/jina-search.ts +275 -0
  151. package/kagi.ts +257 -0
  152. package/keenable.ts +222 -0
  153. package/kimi-search.ts +209 -0
  154. package/linkup.ts +170 -0
  155. package/mcp-cli.ts +40 -0
  156. package/mcp-server.ts +84 -0
  157. package/mcp-tool-definitions.ts +143 -0
  158. package/mistral-search.ts +268 -0
  159. package/ninerouter.ts +92 -0
  160. package/offtopic-judge.ts +72 -0
  161. package/ollama.ts +237 -0
  162. package/openai-search.ts +855 -0
  163. package/package.json +108 -4
  164. package/page-query.ts +185 -0
  165. package/parallel-mcp.ts +255 -0
  166. package/parallel.ts +373 -0
  167. package/pdf-extract.ts +447 -0
  168. package/perplexity.ts +245 -0
  169. package/pi-mcp.ts +139 -0
  170. package/pi-session-results.ts +40 -0
  171. package/pi-web-fetch-demo.mp4 +0 -0
  172. package/promise-try.d.ts +7 -0
  173. package/querit.ts +394 -0
  174. package/query-rewrite.ts +84 -0
  175. package/render-search-error.ts +170 -0
  176. package/retrieval-only.ts +102 -0
  177. package/rsc-extract.ts +338 -0
  178. package/search-answer-formatting.ts +11 -0
  179. package/search-result-count-normalization.ts +4 -0
  180. package/searchinfinity.ts +246 -0
  181. package/searxng.ts +236 -0
  182. package/source-check.ts +269 -0
  183. package/ssrf-protection.ts +602 -0
  184. package/storage.ts +547 -0
  185. package/summary-model-scope.ts +72 -0
  186. package/summary-review.ts +476 -0
  187. package/tabstack.ts +289 -0
  188. package/tavily.ts +257 -0
  189. package/tinyfish.ts +373 -0
  190. package/tool-activation.ts +169 -0
  191. package/tool-arguments.ts +23 -0
  192. package/upgrade-notice.ts +47 -0
  193. package/utils.ts +693 -0
  194. package/valyu.ts +177 -0
  195. package/video-extract.ts +398 -0
  196. package/web-tool-contract.ts +93 -0
  197. package/web-tool-core.ts +1810 -0
  198. package/xai-search.ts +443 -0
  199. package/you.ts +165 -0
  200. package/youtube-extract.ts +336 -0
  201. package/zai.ts +161 -0
package/bocha.ts ADDED
@@ -0,0 +1,203 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { activityMonitor } from "./activity.ts";
3
+ import { normalizeDomain } from "./domain-filter-normalization.ts";
4
+ import { formatSearchResultsAsAnswer } from "./search-answer-formatting.ts";
5
+ import type { SearchOptions, SearchResponse } from "./perplexity.ts";
6
+ import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
7
+ import { getWebSearchConfigPath, resolveProviderApiUrl, fetchWithCredentialRedirects } from "./utils.ts";
8
+
9
+ const BOCHA_SEARCH_URL = "https://api.bochaai.com/v1/web-search";
10
+ const CONFIG_PATH = getWebSearchConfigPath();
11
+ const SEARCH_TIMEOUT_MS = 60_000;
12
+
13
+ interface WebSearchConfig {
14
+ bochaBaseUrl?: unknown;
15
+ bochaApiKey?: unknown;
16
+ }
17
+
18
+ let cachedConfig: WebSearchConfig | null = null;
19
+
20
+ function loadConfig(): WebSearchConfig {
21
+ if (cachedConfig) return cachedConfig;
22
+ if (!existsSync(CONFIG_PATH)) {
23
+ cachedConfig = {};
24
+ return cachedConfig;
25
+ }
26
+ const raw = readFileSync(CONFIG_PATH, "utf-8");
27
+ let parsed: unknown;
28
+ try {
29
+ parsed = JSON.parse(raw);
30
+ } catch (err) {
31
+ const message = err instanceof Error ? err.message : String(err);
32
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
33
+ }
34
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
35
+ throw new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);
36
+ }
37
+ cachedConfig = parsed as WebSearchConfig;
38
+ return cachedConfig;
39
+ }
40
+
41
+ async function getApiKey(signal?: AbortSignal): Promise<string | null> {
42
+ return resolveCredential({
43
+ provider: "Bocha",
44
+ configuredValue: loadConfig().bochaApiKey,
45
+ environmentValue: process.env.BOCHA_API_KEY,
46
+ signal,
47
+ });
48
+ }
49
+
50
+ async function requireApiKey(signal?: AbortSignal): Promise<string> {
51
+ const apiKey = await getApiKey(signal);
52
+ if (!apiKey) {
53
+ throw new Error(
54
+ "Bocha API key not found. Either:\n" +
55
+ ` 1. Create ${CONFIG_PATH} with { "bochaApiKey": "your-key" }\n` +
56
+ " 2. Set BOCHA_API_KEY environment variable\n" +
57
+ "Create a key at https://open.bochaai.com/",
58
+ );
59
+ }
60
+ return apiKey;
61
+ }
62
+
63
+ function normalizeCount(value: number | undefined): number {
64
+ if (typeof value !== "number" || !Number.isFinite(value)) return 8;
65
+ return Math.max(1, Math.min(Math.floor(value), 20));
66
+ }
67
+
68
+ function mapFreshness(value: SearchOptions["recencyFilter"]): string {
69
+ switch (value) {
70
+ case "day": return "oneDay";
71
+ case "week": return "oneWeek";
72
+ case "month": return "oneMonth";
73
+ case "year": return "oneYear";
74
+ default: return "noLimit";
75
+ }
76
+ }
77
+
78
+ interface DomainFilters {
79
+ include: string[];
80
+ exclude: string[];
81
+ }
82
+
83
+ function parseDomainFilter(domainFilter: string[] | undefined): DomainFilters {
84
+ const filters: DomainFilters = { include: [], exclude: [] };
85
+ for (const raw of domainFilter ?? []) {
86
+ const domain = normalizeDomain(raw);
87
+ if (!domain) continue;
88
+ const target = raw.trim().startsWith("-") ? filters.exclude : filters.include;
89
+ if (!target.includes(domain)) target.push(domain);
90
+ }
91
+ return filters;
92
+ }
93
+
94
+ function passesDomainFilters(url: string, filters: DomainFilters): boolean {
95
+ if (filters.include.length === 0 && filters.exclude.length === 0) return true;
96
+ let hostname: string;
97
+ try {
98
+ hostname = new URL(url).hostname.toLowerCase();
99
+ } catch {
100
+ return false;
101
+ }
102
+ const matches = (domain: string) => hostname === domain || hostname.endsWith(`.${domain}`);
103
+ if (filters.exclude.some(matches)) return false;
104
+ return filters.include.length === 0 || filters.include.some(matches);
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(`Bocha API returned invalid response: ${message}`);
113
+ }
114
+
115
+ function firstString(...values: unknown[]): string | null {
116
+ for (const value of values) {
117
+ if (typeof value === "string" && value.trim()) return value.trim();
118
+ }
119
+ return null;
120
+ }
121
+
122
+ function parseSearchResponse(value: unknown): { results: SearchResponse["results"] } {
123
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw invalidResponse("expected an object envelope");
124
+ const envelope = value as Record<string, unknown>;
125
+ if (envelope.code !== undefined && Number(envelope.code) !== 200) {
126
+ throw invalidResponse(`code ${String(envelope.code)}: ${firstString(envelope.msg) ?? "unknown error"}`);
127
+ }
128
+ const data = envelope.data;
129
+ const pages = (typeof data === "object" && data !== null && !Array.isArray(data))
130
+ ? (data as Record<string, unknown>).webPages
131
+ : undefined;
132
+ const items = (typeof pages === "object" && pages !== null && !Array.isArray(pages))
133
+ ? (pages as Record<string, unknown>).value
134
+ : undefined;
135
+ if (!Array.isArray(items)) throw invalidResponse("missing data.webPages.value array");
136
+ const results: SearchResponse["results"] = [];
137
+ for (const item of items) {
138
+ if (!item || typeof item !== "object" || Array.isArray(item)) continue;
139
+ const entry = item as Record<string, unknown>;
140
+ const url = firstString(entry.url, entry.link, entry.href);
141
+ if (!url) continue;
142
+ const title = firstString(entry.title, entry.name) ?? url;
143
+ const snippet = firstString(entry.summary, entry.snippet, entry.description, entry.content) ?? "";
144
+ results.push({ title, url, snippet });
145
+ }
146
+ return { results };
147
+ }
148
+
149
+ export function isBochaAvailable(): boolean {
150
+ return hasCredentialSource({ provider: "Bocha", configuredValue: loadConfig().bochaApiKey, environmentValue: process.env.BOCHA_API_KEY });
151
+ }
152
+
153
+ export async function searchWithBocha(query: string, options: SearchOptions = {}): Promise<SearchResponse> {
154
+ const apiKey = await requireApiKey(options.signal);
155
+ const numResults = normalizeCount(options.numResults);
156
+ const filters = parseDomainFilter(options.domainFilter);
157
+ const activityId = activityMonitor.logStart({ type: "api", query });
158
+ let response: Response;
159
+ try {
160
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("bocha", BOCHA_SEARCH_URL, loadConfig().bochaBaseUrl), {
161
+ method: "POST",
162
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", Accept: "application/json" },
163
+ body: JSON.stringify({ query, count: numResults, freshness: mapFreshness(options.recencyFilter), summary: true }),
164
+ signal: options.signal ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS), options.signal]) : AbortSignal.timeout(SEARCH_TIMEOUT_MS),
165
+ }, ["Authorization"]);
166
+ } catch (err) {
167
+ const message = errorMessage(err);
168
+ const redactedMessage = redactCredential(message, apiKey);
169
+ if (redactedMessage.toLowerCase().includes("abort")) activityMonitor.logComplete(activityId, 0);
170
+ else activityMonitor.logError(activityId, redactedMessage);
171
+ if (redactedMessage === message) throw err;
172
+ const redactedError = new Error(redactedMessage);
173
+ if (err instanceof Error) redactedError.name = err.name;
174
+ throw redactedError;
175
+ }
176
+ if (!response.ok) {
177
+ activityMonitor.logComplete(activityId, response.status);
178
+ const errorText = redactCredential(await response.text(), apiKey);
179
+ throw new Error(`Bocha API error ${response.status}: ${errorText.slice(0, 300)}`);
180
+ }
181
+ let rawData: unknown;
182
+ try {
183
+ rawData = await response.json();
184
+ } catch (err) {
185
+ activityMonitor.logComplete(activityId, response.status);
186
+ throw new Error(`Bocha API returned invalid JSON: ${errorMessage(err)}`);
187
+ }
188
+ let parsed: { results: SearchResponse["results"] };
189
+ try {
190
+ parsed = parseSearchResponse(rawData);
191
+ } catch (err) {
192
+ const message = errorMessage(err);
193
+ const redactedMessage = redactCredential(message, apiKey);
194
+ activityMonitor.logError(activityId, redactedMessage);
195
+ if (redactedMessage === message) throw err;
196
+ const redactedError = new Error(redactedMessage);
197
+ if (err instanceof Error) redactedError.name = err.name;
198
+ throw redactedError;
199
+ }
200
+ activityMonitor.logComplete(activityId, response.status);
201
+ const results = parsed.results.filter((result) => passesDomainFilters(result.url, filters)).slice(0, numResults);
202
+ return { answer: formatSearchResultsAsAnswer(results), results };
203
+ }
@@ -0,0 +1,176 @@
1
+ const DEFAULT_SAFETY_MARGIN_MS = 100;
2
+ const DEFAULT_MAX_WAIT_MS = 30_000;
3
+
4
+ export interface BraveRateLimitBucket {
5
+ limit: number;
6
+ windowSeconds: number | null;
7
+ remaining: number;
8
+ resetSeconds: number;
9
+ }
10
+
11
+ export interface BraveRateLimitCoordinatorOptions {
12
+ now?: () => number;
13
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
14
+ safetyMarginMs?: number;
15
+ maxWaitMs?: number;
16
+ }
17
+
18
+ function parseNumberList(value: string | null): number[] {
19
+ if (!value) return [];
20
+ return value.split(",").map(part => Number(part.trim()));
21
+ }
22
+
23
+ function parsePolicyWindows(value: string | null): Array<number | null> {
24
+ if (!value) return [];
25
+ return value.split(",").map(part => {
26
+ const match = /(?:^|;)\s*w=(\d+(?:\.\d+)?)\s*(?:;|$)/i.exec(part.trim());
27
+ if (!match) return null;
28
+ const seconds = Number(match[1]);
29
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
30
+ });
31
+ }
32
+
33
+ /** Parse Brave's parallel rate-limit bucket headers by list position. */
34
+ export function parseBraveRateLimitHeaders(headers: Headers): BraveRateLimitBucket[] {
35
+ const limits = parseNumberList(headers.get("x-ratelimit-limit"));
36
+ const remaining = parseNumberList(headers.get("x-ratelimit-remaining"));
37
+ const resets = parseNumberList(headers.get("x-ratelimit-reset"));
38
+ const windows = parsePolicyWindows(headers.get("x-ratelimit-policy"));
39
+ const count = Math.max(limits.length, remaining.length, resets.length, windows.length);
40
+ const buckets: BraveRateLimitBucket[] = [];
41
+
42
+ for (let index = 0; index < count; index++) {
43
+ const limit = limits[index];
44
+ const left = remaining[index];
45
+ const resetSeconds = resets[index];
46
+ if (![limit, left, resetSeconds].every(Number.isFinite) || limit < 0 || left < 0 || resetSeconds < 0) continue;
47
+ buckets.push({
48
+ limit,
49
+ windowSeconds: windows[index] ?? null,
50
+ remaining: left,
51
+ resetSeconds,
52
+ });
53
+ }
54
+ return buckets;
55
+ }
56
+
57
+ export function parseRetryAfterMs(headers: Headers, now = Date.now()): number | null {
58
+ const value = headers.get("retry-after")?.trim();
59
+ if (!value) return null;
60
+ const seconds = Number(value);
61
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;
62
+ const date = Date.parse(value);
63
+ if (!Number.isFinite(date)) return null;
64
+ return Math.max(0, date - now);
65
+ }
66
+
67
+ // Prepaid plans report a monthly bucket with limit 0: it always reads
68
+ // remaining 0 but never gates requests.
69
+ function exhaustedBuckets(headers: Headers): BraveRateLimitBucket[] {
70
+ return parseBraveRateLimitHeaders(headers).filter(bucket => bucket.limit > 0 && bucket.remaining === 0);
71
+ }
72
+
73
+ export function defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {
74
+ if (signal?.aborted) return Promise.reject(new Error("Aborted"));
75
+ return new Promise((resolve, reject) => {
76
+ const cleanup = () => signal?.removeEventListener("abort", onAbort);
77
+ const timer = setTimeout(() => {
78
+ cleanup();
79
+ resolve();
80
+ }, ms);
81
+ const onAbort = () => {
82
+ clearTimeout(timer);
83
+ cleanup();
84
+ reject(new Error("Aborted"));
85
+ };
86
+ signal?.addEventListener("abort", onAbort, { once: true });
87
+ });
88
+ }
89
+
90
+ export function formatWait(ms: number): string {
91
+ const seconds = Math.ceil(ms / 1000);
92
+ if (seconds < 60) return `${seconds}s`;
93
+ const minutes = Math.ceil(seconds / 60);
94
+ if (minutes < 60) return `${minutes}m`;
95
+ const hours = Math.ceil(minutes / 60);
96
+ return `${hours}h`;
97
+ }
98
+
99
+ export class BraveRateLimitCoordinator {
100
+ private queue: Promise<void> = Promise.resolve();
101
+ private blockedUntil = 0;
102
+ private readonly now: () => number;
103
+ private readonly sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
104
+ private readonly safetyMarginMs: number;
105
+ private readonly maxWaitMs: number;
106
+
107
+ constructor(options: BraveRateLimitCoordinatorOptions = {}) {
108
+ this.now = options.now ?? Date.now;
109
+ this.sleep = options.sleep ?? defaultSleep;
110
+ this.safetyMarginMs = options.safetyMarginMs ?? DEFAULT_SAFETY_MARGIN_MS;
111
+ this.maxWaitMs = options.maxWaitMs ?? DEFAULT_MAX_WAIT_MS;
112
+ }
113
+
114
+ run<T>(operation: () => Promise<T>, signal?: AbortSignal): Promise<T> {
115
+ const scheduled = this.queue.then(async () => {
116
+ await this.waitForAvailability(signal);
117
+ if (signal?.aborted) throw new Error("Aborted");
118
+ return operation();
119
+ });
120
+ this.queue = scheduled.then(() => undefined, () => undefined);
121
+ if (!signal) return scheduled;
122
+ if (signal.aborted) return Promise.reject(new Error("Aborted"));
123
+ return new Promise<T>((resolve, reject) => {
124
+ const onAbort = () => reject(new Error("Aborted"));
125
+ signal.addEventListener("abort", onAbort, { once: true });
126
+ scheduled.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
127
+ });
128
+ }
129
+
130
+ observe(headers: Headers): void {
131
+ const exhausted = exhaustedBuckets(headers);
132
+ if (exhausted.length === 0) return;
133
+ const resetMs = Math.max(...exhausted.map(bucket => bucket.resetSeconds * 1000));
134
+ this.blockFor(resetMs);
135
+ }
136
+
137
+ retryDelay(headers: Headers): number | null {
138
+ const advertised = parseRetryAfterMs(headers, this.now());
139
+ const exhausted = exhaustedBuckets(headers);
140
+ const bucketDelay = exhausted.length > 0
141
+ ? Math.max(...exhausted.map(bucket => bucket.resetSeconds * 1000))
142
+ : null;
143
+ if (advertised === null && bucketDelay === null) return null;
144
+ return Math.max(advertised ?? 0, bucketDelay ?? 0) + this.safetyMarginMs;
145
+ }
146
+
147
+ recordRetryDelay(delayMs: number): void {
148
+ this.blockFor(delayMs, false);
149
+ }
150
+
151
+ async waitForRecordedCooldown(signal?: AbortSignal): Promise<void> {
152
+ await this.waitForAvailability(signal);
153
+ }
154
+
155
+ async waitForRetry(delayMs: number, signal?: AbortSignal): Promise<void> {
156
+ this.recordRetryDelay(delayMs);
157
+ await this.waitForRecordedCooldown(signal);
158
+ }
159
+
160
+ private blockFor(delayMs: number, addMargin = true): void {
161
+ const boundedDelay = Math.max(0, delayMs) + (addMargin ? this.safetyMarginMs : 0);
162
+ this.blockedUntil = Math.max(this.blockedUntil, this.now() + boundedDelay);
163
+ }
164
+
165
+ private async waitForAvailability(signal?: AbortSignal): Promise<void> {
166
+ const waitMs = Math.max(0, this.blockedUntil - this.now());
167
+ if (waitMs === 0) return;
168
+ this.assertWaitIsBounded(waitMs);
169
+ await this.sleep(waitMs, signal);
170
+ }
171
+
172
+ private assertWaitIsBounded(waitMs: number): void {
173
+ if (waitMs <= this.maxWaitMs) return;
174
+ throw new Error(`Brave Search quota exhausted; estimated reset in ${formatWait(waitMs)}. Refusing to wait longer than ${formatWait(this.maxWaitMs)} inside one search call.`);
175
+ }
176
+ }
package/brave.ts ADDED
@@ -0,0 +1,247 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { activityMonitor } from "./activity.ts";
3
+ import { BraveRateLimitCoordinator } from "./brave-rate-limit.ts";
4
+ import { normalizeDomain } from "./domain-filter-normalization.ts";
5
+ import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
6
+ import type { SearchOptions, SearchResult, SearchResponse } from "./perplexity.ts";
7
+ import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
8
+ import { fetchWithCredentialRedirects, getWebSearchConfigPath, resolveApiBaseUrl } from "./utils.ts";
9
+
10
+ const BRAVE_API_BASE_URL = "https://api.search.brave.com/res/v1";
11
+ const CONFIG_PATH = getWebSearchConfigPath();
12
+ const SEARCH_TIMEOUT_MS = 30_000;
13
+ const braveRateLimit = new BraveRateLimitCoordinator();
14
+
15
+ interface WebSearchConfig {
16
+ braveApiKey?: unknown;
17
+ braveBaseUrl?: unknown;
18
+ }
19
+
20
+ interface NormalizedDomainFilters {
21
+ allowed: string[];
22
+ blocked: string[];
23
+ }
24
+
25
+ let cachedConfig: WebSearchConfig | null = null;
26
+
27
+ function loadConfig(): WebSearchConfig {
28
+ if (cachedConfig) return cachedConfig;
29
+ if (!existsSync(CONFIG_PATH)) {
30
+ cachedConfig = {};
31
+ return cachedConfig;
32
+ }
33
+
34
+ const raw = readFileSync(CONFIG_PATH, "utf-8");
35
+ try {
36
+ cachedConfig = JSON.parse(raw) as WebSearchConfig;
37
+ return cachedConfig;
38
+ } catch (err) {
39
+ const message = err instanceof Error ? err.message : String(err);
40
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
41
+ }
42
+ }
43
+
44
+ async function getApiKey(signal?: AbortSignal): Promise<string | null> {
45
+ return resolveCredential({
46
+ provider: "Brave",
47
+ configuredValue: loadConfig().braveApiKey,
48
+ environmentValue: process.env.BRAVE_API_KEY,
49
+ signal,
50
+ });
51
+ }
52
+
53
+ function getApiUrl(): string {
54
+ return `${resolveApiBaseUrl({
55
+ configKey: "braveBaseUrl",
56
+ configuredValue: loadConfig().braveBaseUrl,
57
+ defaultValue: BRAVE_API_BASE_URL,
58
+ environmentKey: "BRAVE_BASE_URL",
59
+ environmentValue: process.env.BRAVE_BASE_URL,
60
+ })}/web/search`;
61
+ }
62
+
63
+ function normalizeDomainFilters(domainFilter: string[] | undefined): NormalizedDomainFilters {
64
+ const filters: NormalizedDomainFilters = { allowed: [], blocked: [] };
65
+ if (!domainFilter?.length) return filters;
66
+
67
+ for (const raw of domainFilter) {
68
+ const domain = normalizeDomain(raw);
69
+ if (!domain) continue;
70
+ const target = raw.trim().startsWith("-") ? filters.blocked : filters.allowed;
71
+ if (!target.includes(domain)) target.push(domain);
72
+ }
73
+
74
+ return filters;
75
+ }
76
+
77
+ function buildBraveQuery(query: string, domainFilter: string[] | undefined): string {
78
+ const filters = normalizeDomainFilters(domainFilter);
79
+ const parts = [query];
80
+
81
+ if (filters.allowed.length === 1) {
82
+ parts.push(`site:${filters.allowed[0]}`);
83
+ } else if (filters.allowed.length > 1) {
84
+ parts.push(filters.allowed.map(domain => `site:${domain}`).join(" OR "));
85
+ }
86
+
87
+ for (const domain of filters.blocked) {
88
+ parts.push(`NOT site:${domain}`);
89
+ }
90
+
91
+ return parts.join(" ");
92
+ }
93
+
94
+ function hostMatchesDomain(hostname: string, domain: string): boolean {
95
+ return hostname === domain || hostname.endsWith(`.${domain}`);
96
+ }
97
+
98
+ function matchesDomainFilters(url: string, filters: NormalizedDomainFilters): boolean {
99
+ if (filters.allowed.length === 0 && filters.blocked.length === 0) return true;
100
+
101
+ let hostname = "";
102
+ try {
103
+ hostname = new URL(url).hostname.toLowerCase();
104
+ } catch {
105
+ return false;
106
+ }
107
+
108
+ if (filters.allowed.length > 0 && !filters.allowed.some(domain => hostMatchesDomain(hostname, domain))) {
109
+ return false;
110
+ }
111
+
112
+ return !filters.blocked.some(domain => hostMatchesDomain(hostname, domain));
113
+ }
114
+
115
+ const HTML_ENTITIES: Record<string, string> = {
116
+ "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": "\"", "&apos;": "'", "&nbsp;": " ",
117
+ "&mdash;": "—", "&ndash;": "–", "&hellip;": "…", "&rsquo;": "’", "&lsquo;": "‘",
118
+ "&rdquo;": "”", "&ldquo;": "“", "&middot;": "·", "&bull;": "•", "&deg;": "°",
119
+ };
120
+
121
+ /** Brave marks matched terms with tags and escapes the rest. */
122
+ function stripHtml(value: string): string {
123
+ return value
124
+ .replace(/<[^>]*>/g, "")
125
+ .replace(/&(?:#(x?)([0-9a-f]+)|[a-z]+);/gi, (entity, hex: string | undefined, digits: string | undefined) => {
126
+ if (!digits) return HTML_ENTITIES[entity.toLowerCase()] ?? entity;
127
+ const code = Number.parseInt(digits, hex ? 16 : 10);
128
+ return code <= 0x10ffff && (code < 0xd800 || code > 0xdfff) ? String.fromCodePoint(code) : entity;
129
+ })
130
+ .trim();
131
+ }
132
+
133
+ export function isBraveAvailable(): boolean {
134
+ return hasCredentialSource({
135
+ provider: "Brave",
136
+ configuredValue: loadConfig().braveApiKey,
137
+ environmentValue: process.env.BRAVE_API_KEY,
138
+ });
139
+ }
140
+
141
+ export async function searchWithBrave(
142
+ query: string,
143
+ options: SearchOptions = {},
144
+ ): Promise<SearchResponse> {
145
+ const apiUrl = getApiUrl();
146
+ const apiKey = await getApiKey(options.signal);
147
+ if (!apiKey) {
148
+ throw new Error(
149
+ "Brave Search API key not found. Either:\n" +
150
+ ` 1. Create ${CONFIG_PATH} with { "braveApiKey": "your-key" }\n` +
151
+ " 2. Set BRAVE_API_KEY environment variable\n" +
152
+ "Get a key at https://brave.com/search/api/",
153
+ );
154
+ }
155
+
156
+ const numResults = normalizeSearchResultCount(options.numResults);
157
+ const domainFilters = normalizeDomainFilters(options.domainFilter);
158
+ const searchQuery = buildBraveQuery(query, options.domainFilter);
159
+ const activityId = activityMonitor.logStart({ type: "api", query: searchQuery });
160
+ const params = new URLSearchParams({
161
+ q: searchQuery,
162
+ count: String(options.domainFilter?.length ? 20 : numResults),
163
+ });
164
+
165
+ if (options.recencyFilter) {
166
+ const freshnessMap: Record<string, string> = {
167
+ day: "pd",
168
+ week: "pw",
169
+ month: "pm",
170
+ year: "py",
171
+ };
172
+ const freshness = freshnessMap[options.recencyFilter];
173
+ if (freshness) params.set("freshness", freshness);
174
+ }
175
+
176
+ try {
177
+ const searchDeadline = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
178
+ const searchSignal = options.signal
179
+ ? AbortSignal.any([searchDeadline, options.signal])
180
+ : searchDeadline;
181
+ const response = await braveRateLimit.run(async () => {
182
+ for (let attempt = 0; attempt < 2; attempt++) {
183
+ const current = await fetchWithCredentialRedirects(`${apiUrl}?${params.toString()}`, {
184
+ method: "GET",
185
+ headers: {
186
+ "X-Subscription-Token": apiKey,
187
+ "Accept": "application/json",
188
+ "Accept-Encoding": "gzip",
189
+ },
190
+ signal: searchSignal,
191
+ }, ["X-Subscription-Token"]);
192
+
193
+ braveRateLimit.observe(current.headers);
194
+ if (current.status !== 429 || attempt === 1) return current;
195
+ const retryDelay = braveRateLimit.retryDelay(current.headers);
196
+ if (retryDelay === null) return current;
197
+ braveRateLimit.recordRetryDelay(retryDelay);
198
+ await current.body?.cancel().catch(() => undefined);
199
+ await braveRateLimit.waitForRecordedCooldown(searchSignal);
200
+ }
201
+ throw new Error("Brave Search retry loop exited unexpectedly");
202
+ }, searchSignal);
203
+
204
+ if (!response.ok) {
205
+ activityMonitor.logError(activityId, `HTTP ${response.status}`);
206
+ const errorText = redactCredential(await response.text(), apiKey);
207
+ throw new Error(`Brave Search API error ${response.status}: ${errorText.slice(0, 300)}`);
208
+ }
209
+
210
+ const data = await response.json() as {
211
+ web?: { results?: Array<{ title?: string; url?: string; description?: string }> };
212
+ };
213
+ activityMonitor.logComplete(activityId, response.status);
214
+
215
+ const results: SearchResult[] = [];
216
+ for (const item of data.web?.results ?? []) {
217
+ if (!item.url || !matchesDomainFilters(item.url, domainFilters)) continue;
218
+ results.push({
219
+ title: stripHtml(item.title || "") || item.url,
220
+ url: item.url,
221
+ snippet: stripHtml(item.description || ""),
222
+ });
223
+ if (results.length >= numResults) break;
224
+ }
225
+
226
+ const answer = results
227
+ .map((result) => {
228
+ if (result.snippet) return `${result.snippet}\nSource: ${result.title} (${result.url})`;
229
+ return `Source: ${result.title} (${result.url})`;
230
+ })
231
+ .join("\n\n");
232
+
233
+ return { answer, results };
234
+ } catch (err) {
235
+ const message = err instanceof Error ? err.message : String(err);
236
+ const redactedMessage = redactCredential(message, apiKey);
237
+ if (redactedMessage.toLowerCase().includes("abort")) {
238
+ activityMonitor.logComplete(activityId, 0);
239
+ } else {
240
+ activityMonitor.logError(activityId, redactedMessage);
241
+ }
242
+ if (redactedMessage === message) throw err;
243
+ const redactedError = new Error(redactedMessage);
244
+ if (err instanceof Error) redactedError.name = err.name;
245
+ throw redactedError;
246
+ }
247
+ }