@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/SECURITY.md ADDED
@@ -0,0 +1,5 @@
1
+ # Security Policy
2
+
3
+ Please report suspected vulnerabilities through GitHub private vulnerability reporting for this repository. Do not post exploit details, secrets, or proof-of-concept payloads in public issues or pull requests.
4
+
5
+ If private vulnerability reporting is unavailable for your account or this repository, open a minimal public issue asking for a private contact path without including technical details.
package/abortable.ts ADDED
@@ -0,0 +1,17 @@
1
+ /** Observe cancellation while awaiting work that cannot itself be cancelled (such as import()). */
2
+ export async function awaitWithAbort<T>(operation: Promise<T>, signal?: AbortSignal): Promise<T> {
3
+ if (!signal) return operation;
4
+ let onAbort: () => void = () => {};
5
+ const aborted = new Promise<never>((_resolve, reject) => {
6
+ onAbort = () => reject(new Error("Aborted"));
7
+ signal.addEventListener("abort", onAbort, { once: true });
8
+ if (signal.aborted) onAbort();
9
+ });
10
+ try {
11
+ const result = await Promise.race([operation, aborted]);
12
+ if (signal.aborted) throw new Error("Aborted");
13
+ return result;
14
+ } finally {
15
+ signal.removeEventListener("abort", onAbort);
16
+ }
17
+ }
package/activity.ts ADDED
@@ -0,0 +1,101 @@
1
+ // Types
2
+ export interface ActivityEntry {
3
+ id: string;
4
+ type: "api" | "fetch";
5
+ startTime: number;
6
+ endTime?: number;
7
+
8
+ // For API calls
9
+ query?: string;
10
+
11
+ // For URL fetches
12
+ url?: string;
13
+
14
+ // Result - status is number (HTTP code) or null (pending/network error)
15
+ status: number | null;
16
+ error?: string;
17
+ }
18
+
19
+ export interface RateLimitInfo {
20
+ used: number;
21
+ max: number;
22
+ oldestTimestamp: number | null;
23
+ windowMs: number;
24
+ }
25
+
26
+ export class ActivityMonitor {
27
+ private entries: ActivityEntry[] = [];
28
+ private readonly maxEntries = 10;
29
+ private listeners = new Set<() => void>();
30
+ private rateLimitInfo: RateLimitInfo = { used: 0, max: 10, oldestTimestamp: null, windowMs: 60000 };
31
+ private nextId = 1;
32
+
33
+ logStart(partial: Omit<ActivityEntry, "id" | "startTime" | "status">): string {
34
+ const id = `act-${this.nextId++}`;
35
+ const entry: ActivityEntry = {
36
+ ...partial,
37
+ id,
38
+ startTime: Date.now(),
39
+ status: null,
40
+ };
41
+ this.entries.push(entry);
42
+ if (this.entries.length > this.maxEntries) {
43
+ this.entries.shift();
44
+ }
45
+ this.notify();
46
+ return id;
47
+ }
48
+
49
+ logComplete(id: string, status: number): void {
50
+ const entry = this.entries.find((e) => e.id === id);
51
+ if (entry) {
52
+ entry.endTime = Date.now();
53
+ entry.status = status;
54
+ this.notify();
55
+ }
56
+ }
57
+
58
+ logError(id: string, error: string): void {
59
+ const entry = this.entries.find((e) => e.id === id);
60
+ if (entry) {
61
+ entry.endTime = Date.now();
62
+ entry.error = error;
63
+ this.notify();
64
+ }
65
+ }
66
+
67
+ getEntries(): readonly ActivityEntry[] {
68
+ return this.entries;
69
+ }
70
+
71
+ getRateLimitInfo(): RateLimitInfo {
72
+ return this.rateLimitInfo;
73
+ }
74
+
75
+ updateRateLimit(info: RateLimitInfo): void {
76
+ this.rateLimitInfo = info;
77
+ this.notify();
78
+ }
79
+
80
+ onUpdate(callback: () => void): () => void {
81
+ this.listeners.add(callback);
82
+ return () => this.listeners.delete(callback);
83
+ }
84
+
85
+ clear(): void {
86
+ this.entries = [];
87
+ this.rateLimitInfo = { used: 0, max: 10, oldestTimestamp: null, windowMs: 60000 };
88
+ this.notify();
89
+ }
90
+
91
+ private notify(): void {
92
+ for (const cb of this.listeners) {
93
+ try {
94
+ cb();
95
+ } catch {
96
+ }
97
+ }
98
+ }
99
+ }
100
+
101
+ export const activityMonitor = new ActivityMonitor();
package/anysearch.ts ADDED
@@ -0,0 +1,188 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { activityMonitor } from "./activity.ts";
3
+ import { formatSearchResultsAsAnswer } from "./search-answer-formatting.ts";
4
+ import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
5
+ import type { ExtractedContent } from "./extract.ts";
6
+ import type { SearchOptions, SearchResponse } from "./perplexity.ts";
7
+ import { redactCredential, resolveCredential } from "./credential-source.ts";
8
+ import { applyDomainFilter } from "./domain-filter-normalization.ts";
9
+ import { getWebSearchConfigPath, resolveProviderApiUrl, fetchWithCredentialRedirects } from "./utils.ts";
10
+
11
+ const ANYSEARCH_API_URL = "https://api.anysearch.com/v1/search";
12
+ // AnySearch caps max_results at 10; asking for more returns 10 silently.
13
+ const ANYSEARCH_MAX_RESULTS = 10;
14
+ const CONFIG_PATH = getWebSearchConfigPath();
15
+ const SEARCH_TIMEOUT_MS = 30_000;
16
+
17
+ interface WebSearchConfig {
18
+ anysearchBaseUrl?: unknown;
19
+ anysearchApiKey?: unknown;
20
+ }
21
+
22
+ interface AnySearchResult {
23
+ title: string;
24
+ url: string;
25
+ snippet: string;
26
+ content: string;
27
+ }
28
+
29
+ interface AnySearchSearchOptions extends SearchOptions {
30
+ includeContent?: boolean;
31
+ }
32
+
33
+ interface AnySearchResponse {
34
+ code: 0;
35
+ data: {
36
+ results: AnySearchResult[];
37
+ metadata: Record<string, unknown>;
38
+ };
39
+ }
40
+
41
+ let cachedConfig: WebSearchConfig | null = null;
42
+
43
+ function loadConfig(): WebSearchConfig {
44
+ if (cachedConfig) return cachedConfig;
45
+ if (!existsSync(CONFIG_PATH)) {
46
+ cachedConfig = {};
47
+ return cachedConfig;
48
+ }
49
+
50
+ const raw = readFileSync(CONFIG_PATH, "utf-8");
51
+ let parsed: unknown;
52
+ try {
53
+ parsed = JSON.parse(raw);
54
+ } catch (err) {
55
+ const message = err instanceof Error ? err.message : String(err);
56
+ throw new Error(`Failed to parse ${CONFIG_PATH}: ${message}`);
57
+ }
58
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
59
+ throw new Error(`Invalid config in ${CONFIG_PATH}: expected a JSON object`);
60
+ }
61
+ cachedConfig = parsed as WebSearchConfig;
62
+ return cachedConfig;
63
+ }
64
+
65
+ async function getApiKey(signal?: AbortSignal): Promise<string | null> {
66
+ return resolveCredential({
67
+ provider: "AnySearch",
68
+ configuredValue: loadConfig().anysearchApiKey,
69
+ environmentValue: process.env.ANYSEARCH_API_KEY,
70
+ signal,
71
+ });
72
+ }
73
+
74
+ function errorMessage(err: unknown): string {
75
+ return err instanceof Error ? err.message : String(err);
76
+ }
77
+
78
+ function invalidResponse(message: string): Error {
79
+ return new Error(`AnySearch API returned invalid response: ${message}`);
80
+ }
81
+
82
+ function parseResponse(value: unknown): AnySearchResponse {
83
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
84
+ throw invalidResponse("expected an object envelope");
85
+ }
86
+ const envelope = value as Record<string, unknown>;
87
+ if (envelope.code !== 0) throw invalidResponse("expected code 0");
88
+ if (!envelope.data || typeof envelope.data !== "object" || Array.isArray(envelope.data)) {
89
+ throw invalidResponse("expected data object");
90
+ }
91
+ const data = envelope.data as Record<string, unknown>;
92
+ if (!Array.isArray(data.results)) throw invalidResponse("expected data.results array");
93
+ if (!data.metadata || typeof data.metadata !== "object" || Array.isArray(data.metadata)) {
94
+ throw invalidResponse("expected data.metadata object");
95
+ }
96
+
97
+ const results: AnySearchResult[] = [];
98
+ for (const [index, value] of data.results.entries()) {
99
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
100
+ throw invalidResponse(`expected data.results[${index}] object`);
101
+ }
102
+ const result = value as Record<string, unknown>;
103
+ const { title, url, snippet, content } = result;
104
+ if (typeof title !== "string") throw invalidResponse(`expected data.results[${index}].title string`);
105
+ if (typeof url !== "string") throw invalidResponse(`expected data.results[${index}].url string`);
106
+ if (typeof snippet !== "string") throw invalidResponse(`expected data.results[${index}].snippet string`);
107
+ if (content !== undefined && content !== null && typeof content !== "string") {
108
+ throw invalidResponse(`expected data.results[${index}].content string`);
109
+ }
110
+ if (!url) throw invalidResponse(`expected data.results[${index}].url to be non-empty`);
111
+ results.push({ title, url, snippet, content: typeof content === "string" ? content : "" });
112
+ }
113
+
114
+ return { code: 0, data: { results, metadata: data.metadata as Record<string, unknown> } };
115
+ }
116
+
117
+ export function isAnySearchAvailable(): boolean {
118
+ return true;
119
+ }
120
+
121
+ export async function searchWithAnySearch(query: string, options: AnySearchSearchOptions = {}): Promise<SearchResponse> {
122
+ const apiKey = await getApiKey(options.signal);
123
+ const numResults = Math.min(normalizeSearchResultCount(options.numResults), ANYSEARCH_MAX_RESULTS);
124
+ const body = { query, max_results: numResults };
125
+ const activityId = activityMonitor.logStart({ type: "api", query });
126
+ let response: Response;
127
+
128
+ try {
129
+ response = await fetchWithCredentialRedirects(resolveProviderApiUrl("anysearch", ANYSEARCH_API_URL, loadConfig().anysearchBaseUrl), {
130
+ method: "POST",
131
+ headers: {
132
+ ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
133
+ "Content-Type": "application/json",
134
+ },
135
+ body: JSON.stringify(body),
136
+ signal: options.signal
137
+ ? AbortSignal.any([AbortSignal.timeout(SEARCH_TIMEOUT_MS), options.signal])
138
+ : AbortSignal.timeout(SEARCH_TIMEOUT_MS),
139
+ }, ["Authorization"]);
140
+ } catch (err) {
141
+ const message = errorMessage(err);
142
+ const redactedMessage = redactCredential(message, apiKey);
143
+ if (redactedMessage.toLowerCase().includes("abort")) activityMonitor.logComplete(activityId, 0);
144
+ else activityMonitor.logError(activityId, redactedMessage);
145
+ if (redactedMessage === message) throw err;
146
+ const redactedError = new Error(redactedMessage);
147
+ if (err instanceof Error) redactedError.name = err.name;
148
+ throw redactedError;
149
+ }
150
+
151
+ if (!response.ok) {
152
+ activityMonitor.logComplete(activityId, response.status);
153
+ const errorText = redactCredential(await response.text(), apiKey);
154
+ throw new Error(`AnySearch API error ${response.status}: ${errorText.slice(0, 300)}`);
155
+ }
156
+
157
+ let rawData: unknown;
158
+ try {
159
+ rawData = await response.json();
160
+ } catch (err) {
161
+ activityMonitor.logComplete(activityId, response.status);
162
+ throw new Error(`AnySearch API returned invalid JSON: ${errorMessage(err)}`);
163
+ }
164
+
165
+ let data: AnySearchResponse;
166
+ try {
167
+ data = parseResponse(rawData);
168
+ } catch (err) {
169
+ activityMonitor.logComplete(activityId, response.status);
170
+ throw err;
171
+ }
172
+
173
+ activityMonitor.logComplete(activityId, response.status);
174
+ const filtered = applyDomainFilter(data.data.results, options.domainFilter).slice(0, numResults);
175
+ const results = filtered.map((result) => ({
176
+ title: result.title,
177
+ url: result.url,
178
+ snippet: result.snippet,
179
+ }));
180
+ const mapped: SearchResponse = { answer: formatSearchResultsAsAnswer(results), results };
181
+ if (options.includeContent) {
182
+ const inlineContent: ExtractedContent[] = filtered
183
+ .filter(result => result.content.length > 0)
184
+ .map(result => ({ url: result.url, title: result.title, content: result.content, error: null }));
185
+ if (inlineContent.length > 0) mapped.inlineContent = inlineContent;
186
+ }
187
+ return mapped;
188
+ }
package/auth-fetch.ts ADDED
@@ -0,0 +1,152 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { parseBrowserCookiePreset, type BrowserCookiePreset } from "./gemini-web-config.ts";
3
+ import { getWebSearchConfigPath } from "./utils.ts";
4
+
5
+ const WEB_SEARCH_CONFIG_PATH = getWebSearchConfigPath();
6
+ const AUTH_PROFILE_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
7
+
8
+ export type AuthFetchRequest = true | string;
9
+ export type AuthFetchCache = "session" | "off";
10
+
11
+ export interface AuthFetchProfile {
12
+ name: string;
13
+ hosts: string[];
14
+ browser?: BrowserCookiePreset;
15
+ chromeProfile?: string;
16
+ redirects: "same-origin";
17
+ cache: AuthFetchCache;
18
+ }
19
+
20
+ interface AuthFetchConfigRoot {
21
+ authFetch?: unknown;
22
+ }
23
+
24
+ export function resolveAuthFetchProfile(request: AuthFetchRequest): AuthFetchProfile {
25
+ const profiles = loadAuthFetchProfiles();
26
+ if (profiles.length === 0) {
27
+ throw new Error(`auth requires at least one authFetch profile in ${WEB_SEARCH_CONFIG_PATH}`);
28
+ }
29
+ if (request === true) {
30
+ if (profiles.length !== 1) {
31
+ throw new Error("auth: true requires exactly one authFetch profile; use a profile name instead");
32
+ }
33
+ return profiles[0];
34
+ }
35
+ const name = request.trim();
36
+ const profile = profiles.find(candidate => candidate.name === name);
37
+ if (!profile) throw new Error(`Unknown authFetch profile: ${name}`);
38
+ return profile;
39
+ }
40
+
41
+ export function assertAuthFetchUrl(profile: AuthFetchProfile, rawUrl: string): URL {
42
+ let url: URL;
43
+ try {
44
+ url = new URL(rawUrl);
45
+ } catch (err) {
46
+ const message = err instanceof Error ? err.message : String(err);
47
+ throw new Error(`Authenticated fetch requires an HTTPS URL: ${message}`);
48
+ }
49
+ if (url.protocol !== "https:") throw new Error("Authenticated fetch requires an HTTPS URL");
50
+ const hostname = normalizeHostname(url.hostname);
51
+ if (!profile.hosts.some(host => hostMatches(hostname, host))) {
52
+ throw new Error(`URL host ${hostname} is not allowed by authFetch profile ${profile.name}`);
53
+ }
54
+ return url;
55
+ }
56
+
57
+ export function authFetchRedirectGuard(profile: AuthFetchProfile, from: URL, to: URL): void {
58
+ if (profile.redirects === "same-origin" && to.origin !== from.origin) {
59
+ throw new Error(`Authenticated fetch refused cross-origin redirect: ${from.origin} -> ${to.origin}`);
60
+ }
61
+ }
62
+
63
+ function loadAuthFetchProfiles(): AuthFetchProfile[] {
64
+ if (!existsSync(WEB_SEARCH_CONFIG_PATH)) return [];
65
+ const raw = readFileSync(WEB_SEARCH_CONFIG_PATH, "utf-8");
66
+ let parsed: AuthFetchConfigRoot;
67
+ try {
68
+ const value: unknown = JSON.parse(raw);
69
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("expected a JSON object");
70
+ parsed = value as AuthFetchConfigRoot;
71
+ } catch (err) {
72
+ const message = err instanceof Error ? err.message : String(err);
73
+ throw new Error(`Failed to parse ${WEB_SEARCH_CONFIG_PATH}: ${message}`);
74
+ }
75
+ if (parsed.authFetch === undefined || parsed.authFetch === null) return [];
76
+ if (typeof parsed.authFetch !== "object" || Array.isArray(parsed.authFetch)) {
77
+ throw new Error(`authFetch in ${WEB_SEARCH_CONFIG_PATH} must be an object`);
78
+ }
79
+ return Object.entries(parsed.authFetch as Record<string, unknown>).map(([name, value]) => parseProfile(name, value));
80
+ }
81
+
82
+ function parseProfile(name: string, value: unknown): AuthFetchProfile {
83
+ if (!AUTH_PROFILE_NAME_PATTERN.test(name)) {
84
+ throw new Error(`authFetch profile name ${JSON.stringify(name)} must start with a letter and contain only letters, numbers, underscores, or hyphens`);
85
+ }
86
+ if (Array.isArray(value)) {
87
+ return { name, hosts: parseHosts(value, `authFetch.${name}`), redirects: "same-origin", cache: "session" };
88
+ }
89
+ if (!value || typeof value !== "object") {
90
+ throw new Error(`authFetch.${name} in ${WEB_SEARCH_CONFIG_PATH} must be an array of hosts or an object`);
91
+ }
92
+ const config = value as Record<string, unknown>;
93
+ if (!Array.isArray(config.hosts)) {
94
+ throw new Error(`authFetch.${name}.hosts in ${WEB_SEARCH_CONFIG_PATH} must be a non-empty array of hostnames`);
95
+ }
96
+ const redirects = config.redirects ?? "same-origin";
97
+ if (redirects !== "same-origin") {
98
+ throw new Error(`authFetch.${name}.redirects in ${WEB_SEARCH_CONFIG_PATH} must be "same-origin"`);
99
+ }
100
+ const cache = config.cache ?? "session";
101
+ if (cache !== "session" && cache !== "off") {
102
+ throw new Error(`authFetch.${name}.cache in ${WEB_SEARCH_CONFIG_PATH} must be "session" or "off"`);
103
+ }
104
+ const chromeProfile = parseChromeProfile(config.chromeProfile, `authFetch.${name}.chromeProfile`);
105
+ const browser = config.browser === undefined || config.browser === null ? undefined : parseBrowserCookiePreset(config.browser, `authFetch.${name}.browser`);
106
+ return {
107
+ name,
108
+ hosts: parseHosts(config.hosts, `authFetch.${name}.hosts`),
109
+ ...(browser ? { browser } : {}),
110
+ ...(chromeProfile ? { chromeProfile } : {}),
111
+ redirects,
112
+ cache,
113
+ };
114
+ }
115
+
116
+ function parseHosts(value: unknown[], label: string): string[] {
117
+ if (value.length === 0) throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must be a non-empty array of hostnames`);
118
+ const hosts = value.map((entry) => {
119
+ if (typeof entry !== "string") throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must contain only hostnames`);
120
+ return parseHost(entry, label);
121
+ });
122
+ return [...new Set(hosts)];
123
+ }
124
+
125
+ function parseHost(value: string, label: string): string {
126
+ const host = normalizeHostname(value.trim());
127
+ if (!host || host.startsWith(".") || host.endsWith(".") || /\s|[\\/?:#@*]/.test(host)) {
128
+ throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} contains an invalid hostname: ${JSON.stringify(value)}`);
129
+ }
130
+ if (host.length > 253 || !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(host)) {
131
+ throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} contains an invalid hostname: ${JSON.stringify(value)}`);
132
+ }
133
+ return host;
134
+ }
135
+
136
+ function parseChromeProfile(value: unknown, label: string): string | undefined {
137
+ if (value === undefined || value === null) return undefined;
138
+ if (typeof value !== "string") throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must be a string`);
139
+ const normalized = value.trim();
140
+ if (!normalized || normalized === "." || normalized === ".." || normalized.includes("/") || normalized.includes("\\")) {
141
+ throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must be a profile directory name, not a path`);
142
+ }
143
+ return normalized;
144
+ }
145
+
146
+ function normalizeHostname(hostname: string): string {
147
+ return hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
148
+ }
149
+
150
+ function hostMatches(hostname: string, allowedHost: string): boolean {
151
+ return hostname === allowedHost || hostname.endsWith(`.${allowedHost}`);
152
+ }
package/baizhi.ts ADDED
@@ -0,0 +1,124 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { isIP } from "node:net";
3
+ import { activityMonitor } from "./activity.ts";
4
+ import { hasCredentialSource, redactCredential, resolveCredential } from "./credential-source.ts";
5
+ import { normalizeDomain } from "./domain-filter-normalization.ts";
6
+ import type { SearchOptions, SearchResponse } from "./perplexity.ts";
7
+ import { normalizeSearchResultCount } from "./search-result-count-normalization.ts";
8
+ import { getWebSearchConfigPath } from "./utils.ts";
9
+
10
+ const MCP_URL = "https://agent-toolkit.app.baizhi.cloud/mcp";
11
+ const SEARCH_TIMEOUT_MS = 60_000;
12
+ const CONFIG_PATH = getWebSearchConfigPath();
13
+
14
+ function credentialOptions() {
15
+ let config: Record<string, unknown> = {};
16
+ if (existsSync(CONFIG_PATH)) {
17
+ try {
18
+ const parsed: unknown = JSON.parse(readFileSync(CONFIG_PATH, "utf8"));
19
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error();
20
+ config = parsed as Record<string, unknown>;
21
+ } catch {
22
+ // JSON parser errors may include a fragment containing a literal key.
23
+ throw new Error(`Invalid configuration in ${CONFIG_PATH}: expected a JSON object`);
24
+ }
25
+ }
26
+ return { provider: "Baizhi", configuredValue: config.baizhiApiKey, environmentValue: process.env.BAIZHI_API_KEY };
27
+ }
28
+
29
+ export function isBaizhiAvailable(): boolean {
30
+ return hasCredentialSource(credentialOptions());
31
+ }
32
+
33
+ function searchArguments(query: string, options: SearchOptions): Record<string, unknown> {
34
+ if (!query.trim()) throw new Error("Baizhi search query must not be empty");
35
+ const domains: string[] = [];
36
+ const excludeDomains: string[] = [];
37
+ for (const raw of options.domainFilter ?? []) {
38
+ const bare = raw.trim().replace(/^-/, "").trim();
39
+ const domain = isIP(bare) ? bare : normalizeDomain(raw);
40
+ if (!domain) throw new Error("Baizhi domain filter must contain a valid domain");
41
+ const target = raw.trim().startsWith("-") ? excludeDomains : domains;
42
+ if (!target.includes(domain)) target.push(domain);
43
+ }
44
+ return {
45
+ query: query.trim(),
46
+ count: normalizeSearchResultCount(options.numResults),
47
+ need_summary: false,
48
+ // The published discovery contract defaults to month, not unrestricted time.
49
+ time_range: options.recencyFilter ?? "month",
50
+ ...(domains.length || excludeDomains.length ? { filter: {
51
+ ...(domains.length ? { domains } : {}),
52
+ ...(excludeDomains.length ? { exclude_domains: excludeDomains } : {}),
53
+ } } : {}),
54
+ };
55
+ }
56
+
57
+ export async function searchWithBaizhi(query: string, options: SearchOptions = {}): Promise<SearchResponse> {
58
+ const args = searchArguments(query, options);
59
+ const timeoutSignal = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
60
+ const signal = options.signal ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal;
61
+ if (signal.aborted) throw new Error("Aborted");
62
+ const apiKey = await resolveCredential({ ...credentialOptions(), signal });
63
+ if (!apiKey) throw new Error("Baizhi API key not found. Set BAIZHI_API_KEY or baizhiApiKey in web-search.json. Get your own key at https://agent-toolkit.app.baizhi.cloud/");
64
+ let headers: Headers;
65
+ try { headers = new Headers({ Authorization: `Bearer ${apiKey}` }); }
66
+ catch { throw new Error("Baizhi credential resolution failed: invalid-header-value"); }
67
+ // Load the protocol client only when this explicit provider is selected.
68
+ const [{ Client }, { StreamableHTTPClientTransport }] = await Promise.all([
69
+ import("@modelcontextprotocol/sdk/client/index.js"),
70
+ import("@modelcontextprotocol/sdk/client/streamableHttp.js"),
71
+ ]);
72
+ let cleaningUp = false;
73
+ const transport = new StreamableHTTPClientTransport(new URL(MCP_URL), {
74
+ requestInit: { headers },
75
+ fetch: async (url, init) => {
76
+ // Fixed endpoint, no redirects: neither credentials nor session IDs can
77
+ // be forwarded to another origin (including MCP discovery redirects).
78
+ if (String(url) !== MCP_URL) throw new Error("Baizhi endpoint changed unexpectedly");
79
+ const requestSignal = cleaningUp ? AbortSignal.timeout(1_500) : signal;
80
+ return fetch(url, { ...init, redirect: "error", signal: !cleaningUp && init?.signal ? AbortSignal.any([init.signal, requestSignal]) : requestSignal });
81
+ },
82
+ reconnectionOptions: { maxRetries: 0, initialReconnectionDelay: 1_000, maxReconnectionDelay: 1_000, reconnectionDelayGrowFactor: 1 },
83
+ });
84
+ const client = new Client({ name: "pi-web-access-baizhi", version: "1.0.0" });
85
+ const activityId = activityMonitor.logStart({ type: "api", query });
86
+ try {
87
+ await client.connect(transport, { signal, timeout: SEARCH_TIMEOUT_MS });
88
+ const result = await client.callTool({ name: "websearch_search", arguments: args }, undefined, { signal, timeout: SEARCH_TIMEOUT_MS });
89
+ if (result.isError) throw new Error("Baizhi search tool returned an error");
90
+ // The public discovery snapshot documents inputs but no outputSchema.
91
+ // Preserve the MCP payload instead of guessing result item field names.
92
+ const parts: string[] = [];
93
+ if (result.structuredContent !== undefined) parts.push(JSON.stringify(result.structuredContent, null, 2));
94
+ for (const item of Array.isArray(result.content) ? result.content : []) {
95
+ if (item.type === "text" && typeof item.text === "string" && item.text.trim()) parts.push(item.text);
96
+ }
97
+ if (!parts.length) throw new Error("Baizhi returned invalid response: no search text or structured content");
98
+ const answer = redactCredential(redactCredential(parts.join("\n\n"), apiKey), JSON.stringify(apiKey).slice(1, -1));
99
+ activityMonitor.logComplete(activityId, 200);
100
+ return { answer, results: [] };
101
+ } catch (err) {
102
+ let message: string;
103
+ if (options.signal?.aborted) message = "Aborted";
104
+ else if (timeoutSignal.aborted) message = "Baizhi request timed out after 60s";
105
+ else {
106
+ const code = err && typeof err === "object" && "code" in err ? err.code : undefined;
107
+ // Never expose remote HTTP/JSON-RPC bodies or nested SDK errors: they
108
+ // can echo credentials in plain, encoded or transformed form.
109
+ message = typeof code === "number" && Number.isInteger(code) && code >= 400 && code <= 599
110
+ ? `Baizhi HTTP ${code} request failed; check your API key, account and service status`
111
+ : err instanceof TypeError ? "Baizhi network request failed"
112
+ : err instanceof SyntaxError || code === -32700 || code === -32602 ? "Baizhi returned invalid response"
113
+ : err instanceof Error && /^Baizhi (search tool returned an error|returned invalid response:)/.test(err.message) ? err.message
114
+ : "Baizhi MCP request failed; check your connection, API key and account status";
115
+ }
116
+ activityMonitor.logError(activityId, message);
117
+ throw new Error(message);
118
+ } finally {
119
+ cleaningUp = true;
120
+ // Best effort, separately bounded DELETE; always close the local streams.
121
+ try { await transport.terminateSession(); } catch { /* Server may not support DELETE. */ }
122
+ await client.close();
123
+ }
124
+ }
package/banner.png ADDED
Binary file